给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
思路1:
初始时,n1 = NULL, n2 = head, n3 = head->next
n2的next赋值为n1
n1 赋值为n2, n2赋值为n3,n3赋值为n3->next
n2的next赋值为n1
n1赋值为n2,n2赋值为n3,n3赋值为n3->next
重复上述操作
结束条件:n2 = NULL
struct ListNode
{
int val;
struct ListNode *next;
};
struct ListNode* reverseList(struct ListNode* head)
{
if (head == NULL)
{
return NULL;
}
struct ListNode* n1 = NULL;
struct ListNode* n2 = head;
struct ListNode* n3 = head->next;
while (n2 != NULL)
{
//翻转
n2->next = n1;
//继续向后走
n1 = n2;
n2 = n3;
if (n3 != NULL)
{
n3 = n3->next;
}
}
return n1;
}
思路2:
创建一个新链表,将原链表的结点取下,不断头插到新的链表
初始条件,新链表表头newHead,初始时是一个空表
取下第一个结点,头插 cur->next = newHead,
移动新链表的表头, newHead = cur;
继续向后走,cur = next, next = cur->next
取下第二个结点,头插
cur->next = newHead
改变新链表的表头,newHead = cur;
继续向后,cur = next, next = cur->next
取下第3个结点,头插
结束条件:cur == NULL
struct ListNode* reverseList(struct ListNode* head)
{
struct ListNode* newHead = NULL;
struct ListNode* cur = head;
while (cur != NULL)
{
struct ListNode* next = cur->next;
//头插
cur->next = newHead;
//改变新链表的表头
newHead = cur;
//继续向后
cur = next;
}
return newHead;
}