将链表进行反转

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 }                

 

posted @ 2022-12-29 17:50  xxx的小菜鸡  阅读(17)  评论(0)    收藏  举报