赞
踩
目录
我们可以用两个指针,一个指向第一个结点,一个指向第二个结点,然后让后一个结点指向前一个节点就好了,但是如果只使用两个指针会存在一个问题:当让后一个结点指向前一个结点的时候,后面的结点会找不到。所以这里需要三个指针方便后续操作。并且最开始要让最左边指针指向NULL,因为反转后的链表最后一个结点后面也会指向NULL。
- struct ListNode* reverseList(struct ListNode* head) {
- typedef struct ListNode ListNode;//重命名
- ListNode* left = NULL;
- ListNode* mid = head;
- ListNode* right;//防止找不到后面的结点
- while (mid!=NULL)
- {
- right = mid->next;
- mid->next = left;
- left = mid;
- mid = right;
- // right=right->next;//如果这样写会存在对空指针的访问
- }
- return left;
- }
- class Solution {
- public:
- ListNode* reverseList(ListNode* head) {
- ListNode* left = NULL;
- ListNode* mid = head;
- ListNode* right;//防止找不到后面的结点
- while (mid!=NULL)
- {
- right = mid->next;
- mid->next = left;
- left = mid;
- mid = right;
- // right=right->next;//如果这样写会存在对空指针的访问
- }
- return left;
- }
- };
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
- struct ListNode* reverseList(struct ListNode* head) {
- typedef struct ListNode ListNode;
- ListNode* cur=head;
- ListNode* newHead=NULL;
- while(cur!=NULL)
- {
- ListNode* next=cur->next;//放在里面不会引起访问空指针的问题
- cur->next=newHead;
- newHead=cur;
- cur=next;
- }
- return newHead;
- }
- class Solution {
- public:
- ListNode* reverseList(ListNode* head) {
- ListNode* cur=head;
- ListNode* newHead=NULL;
- while(cur!=NULL)
- {
- ListNode* next=cur->next;//放在里面不会引起访问空指针的问题
- cur->next=newHead;
- newHead=cur;
- cur=next;
- }
- return newHead;
- }
- };
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
此方法跟三个指针的方法相似,应该会稍微好理解些。
开始进入递归函数:
完成第一次反转:
递归反转:
- struct ListNode* reverse(struct ListNode* pre,struct ListNode* cur)
- {
- if(cur==NULL)//递归出口
- return pre;
- struct ListNode* late=cur->next;
- cur->next=pre;
- return reverse(cur,late);
- }
- struct ListNode* reverseList(struct ListNode* head){
- return reverse(NULL,head);
- }
- class Solution {
- public:
- ListNode* reverse(ListNode* pre,ListNode* cur)
- {
- if(cur==NULL)//递归出口
- return pre;
- ListNode* late=cur->next;
- cur->next=pre;
- return reverse(cur,late);
- }
- ListNode* reverseList(ListNode* head) {
- return reverse(NULL,head);
- }
- };
先递归到最后一个结点后,回来时再反转。
- struct ListNode* reverseList(struct ListNode* head){
- typedef struct ListNode ListNode;
- if(head==NULL||head->next==NULL)//递归结束条件
- return head;
- ListNode* newHead=reverseList(head->next);//开始进入
- head->next->next=head;
- head->next=NULL;
- return newHead;
- }
- class Solution {
- public:
- ListNode* reverseList(ListNode* head) {
- if(head==NULL||head->next==NULL)//递归结束条件
- return head;
- ListNode* newHead=reverseList(head->next);//开始进入
- head->next->next=head;
- head->next=NULL;
- return newHead;
- }
- };
《道德经·第三十七章》:
不欲以静,天下将自定。
解释:不起贪欲而趋于平静,天下便自然复归于安定。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。