剑指 Offer 24. 反转链表&力扣206

tech2022-09-10  93

题目: 定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。

方法一:迭代翻转+就地翻转+指针后移

函数代码:

class Solution { public: ListNode* reverseList(ListNode* head) { if(!head) { return NULL; } ListNode *pre=NULL; ListNode *cur=head; while(cur){ ListNode *next=cur->next; cur->next=pre; pre=cur; cur=next; } return pre; } };

方法二: 递归

1->2->3->4->5 在head到了4时,(递归进去是4->next),在递归最最后时p=4->next,p用来保存尾结点5

head->next->nexthead为5指向4,5->4,翻转核心部分,之后4->next=NULL;

class Solution { public: ListNode* reverseList(ListNode* head) { if(!head||!head->next) { return head; } ListNode *p=reverseList(head->next); head->next->next=head; head->next=NULL; return p; } };
最新回复(0)