单链表逆转最重要的就是定义一个节点,作为转序的第一个节点,然后将原链表节点依次删除,依次添加到转序的节点上
1、取NULL作为第一个节点,即作为尾节点
List_S* reverseList(List_S* head)
{
List_S* p;
List_S* temp;
temp = VOS_NULL;
while(head)
{
p = head->next;
head->next = temp;
temp = head;
head = p;
}
return temp;
}
2、申请一块内存作为首节点,将原链表首节点数据赋值给该节点,然后转序首节点前移,依次赋值,最后转序后首节点与第二个节点相同,删除首节点
List_S* reverseList2(List_S* head)
{
List_S* p;
List_S* reHead;
reHead = (List_S*)malloc(sizeof(List_S));
if (reHead == NULL)
{
return NULL;
}
reHead->next = NULL;
while(head)
{
p = head->next;
reHead->data = head->data;
head->next = reHead;
reHead = head;
head = p;
}
head = reHead->next;
free(reHead);
return head;
}