反转单链表
本文采用的方式是:对结点一个一个操作的,每次把后面的一个结点抛到前面,不需要开辟另外的内存空间,效率较高。
struct ListNode
{
int data;
ListNode *next;
};
ListNode *ListReverse(ListNode *head)
{
if(head == NULL)
return NULL;
ListNode *pre, *cur, *next;
pre = head;
cur = pre->next;
while(cur)
{
next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
head->next = NULL;
head = pre;
return head;
}
反转双链表
本文采用的方式是:交换每个节点的前向指针和后向指针,然后调整链表的头指针和尾指针。
struct ListNode
{
int data;
ListNode *pre;
ListNode *next;
};
ListNode *ListReverse(ListNode *head)
{
if(head == NULL)
return NULL;
ListNode *pre = NULL;
ListNode *next = NULL
cur = head;
while(cur)
{
next = cur->next;
cur->next = pre;
cur->pre = next;
pre = cur;
cur = next;
}
return cur;
}