简单单链表实现
这里主要是实现了一个单链表,不带头节点的单链表,使用了二级指针。如果是带头节点的链表,其只要一级指针就可以了。
接下来是一个单链表翻转的函数。
typedef struct ListNode
{
struct ListNode *pNext;
int elem;
}ListNode;
void reverseList(ListNode **L)
{
ListNode *newL = NULL;
ListNode *temp = NULL;
ListNode *pL = NULL;
if((L== NULL) || (*L ==NULL))
{
return;
}
pL = *L;
while(pL != NULL)
{
temp = (ListNode *)malloc(sizeof(ListNode));
temp->elem = pL->elem;
temp->pNext = newL;
newL = temp;
(*L) = pL->pNext;
free(pL);
pL = *L;
}
*L = newL;
}
void addNode(ListNode **L, int elem)
{
ListNode *temp = NULL;
if((L == NULL) )
{
return;
}
temp = (ListNode *)malloc(sizeof(ListNode));
memset(temp, 0, sizeof(ListNode));
temp->elem = elem;
temp->pNext = (*L);
(*L) = temp;
//printf("--%d--\n", temp->elem);
}
void printList(ListNode *L)
{
ListNode *p = NULL;
if(L == NULL)
{
return;
}
p = L;
while(p != NULL)
{
printf("%d\t", p->elem);
p = p->pNext;
}
printf("\n");
}
int main()
{
int a[4]= {1, 2, 3, 4};
int i = 0;
ListNode *L = NULL;
for(i = 0; i < 4; i ++)
{
addNode(&L, a[i]);
}
printList(L);
reverseList(&L);
printList(L);
}