剑指Offer-反转链表

82 阅读2分钟

题目

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

思考题:

  • 请同时实现迭代版本和递归版本。

数据范围

链表长度 [0,30][0,30]。

样例

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

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

解析(参考y总)

法一、迭代法
将所有结点的next指针指向前驱结点。单链表在迭代时不能直接找到前驱结点,所以需要一个额外的指针保存前驱结点,且在改变当前结点next指针前要保存后继结点。
法二、递归法
这个函数需要能反转链表,且返回新链表的头结点。所以就可以先递归head->next,这样就可以将以head->next为头结点的链表翻转并得到原链表的尾结点 ,此时head->next是新链表的尾结点,再将它的next指针指向head,然后将head->next指向空就成功反转链表,且新的头结点是tail。

代码

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) {
        if (!head || !head->next) return head;
        
        auto a = head, b = head->next;
        while (b)
        {
            auto c = b->next;
            b->next = a;
            a = b;
            b = c;
        }
        head->next = NULL;
        return a;
    }
};
/**
 * 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 || !head->next) return head;
        ListNode* tail = reverseList(head->next);
        head->next->next = head;
        head->next = nullptr;
        return tail;
    }
};

Python

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

class Solution:
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head or not head.next:
            return head
        a, b = head, head.next
        while b:
            c = b.next
            b.next = a
            a = b
            b = c
        head.next = None
        return a
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head or not head.next:
            return head
        tail = self.reverseList(head.next)
        head.next.next = head
        head.next = None
        return tail

GO

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func reverseList(head *ListNode) *ListNode {
    var a *ListNode
    a = nil
    b := head
    for b != nil {
        c := b.Next
        b.Next = a
        a = b
        b = c
    }
    return a
}
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func reverseList(head *ListNode) *ListNode {
    if head == nil || head.Next == nil {
        return head
    }
    tail := reverseList(head.Next)
    head.Next.Next = head
    head.Next = nil
    return tail
}