206. 反转链表

反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

用一个变量记录pre,一个变量记录next,不断更新current.next = pre

注意更新 cur 和 pre 的位置, 否则有可能出现溢出

python
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        if not head:return None
        prev=None
        cur=head
        while cur:
            cur.next,prev,cur=prev,cur,cur.next
        return prev

Java
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode pre=null,cur=head;
        while(cur!=null){
            ListNode next=cur.next;
            cur.next=pre;
            pre=cur;
            cur=next;
        }
        return pre;
    }
}

单链表也是递归结构,因此,也可以使用递归

  1. 除第一个节点外,递归将链表 reverse
  2. 将第一个节点添加到已 reverse 的链表之后
  3. 每次需要保存已经 reverse 的链表的头节点和尾节点

c++

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
//普通递归
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode* tail=nullptr;
        return reverseRecursive(head,tail);
    }
    ListNode* reverseRecursive(ListNode* head,ListNode*&tail){
        if(head==nullptr){
            tail=nullptr;
            return head;
        }
        if(head->next==nullptr){
            tail=head;
            return head;
        }
        auto h=reverseRecursive(head->next,tail);
        if(tail!=nullptr){
            tail->next=head;
            tail=head;
            head->next=nullptr;
        }
        return h;
    }
};
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
 //(类似)尾递归
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(head==nullptr)return head;
        return revreseRecursive(nullptr,head,head->next);
    }
    ListNode* revreseRecursive(ListNode* prev,ListNode* head,ListNode* next){
        if(next==nullptr)return head;
        auto n=next->next;
        next->next=head;
        head->next=prev;
        return revreseRecursive(head,next,n);
    }
};

python

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        if not head or not head.next:return head
        ans=self.reverseList(head.next)
        head.next.next=head
        head.next=None
        return ans
posted @ 2020-05-24 10:48  XXXSANS  阅读(146)  评论(0编辑  收藏  举报