首页 > 其他分享 >将链表进行反转

将链表进行反转

时间:2022-12-29 18:01:45浏览次数:39  
标签:pre head ListNode cur 反转 next 链表 return 进行

1:在完成这道题之前有两个方法去完成,一个是递归。一个非递归。

殊途同归都是反转相邻的两个节点

递归的方法:

class Solution {
public:
    ListNode* reverse(ListNode* pre,ListNode* cur)
    {
        if(cur == nullptr) return pre;
        ListNode* temp = cur->next;
        cur->next = pre;
        return reverse(cur,temp);
    }
    ListNode* reverseList(ListNode* head) {
        return reverse(nullptr,head);
    }
};
View Code

 非递归的方式:

 1 class Solution {
 2 public:
 3     ListNode* reverseList(ListNode* head) {
 4       Listnode* cur = head;
 5       Listnode* pre = null;
 6       Listnode* tail;
 7       while(cur)
 8       {
 9             tail = head->next;
10             cur->next = pre;
11             pre= cur;
12             cur = tail;
13        }  
14         return pre;
15     }
16 }                

 

标签:pre,head,ListNode,cur,反转,next,链表,return,进行
From: https://www.cnblogs.com/wenwenaolin/p/17013141.html

相关文章