返回

剑指offer24反转链表,比武林秘籍还精彩的算法探索之旅

闲谈

问题

在《剑指offer24反转链表》中,我们面临的挑战是编写一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。链表中每个节点都包含一个整数值,且链表中可能有环。

算法思路

双指针迭代法是我们破解这一难题的法宝。具体步骤如下:

  1. 初始化两个指针:precur,分别指向链表的头节点和第一个节点。
  2. 在遍历链表的过程中,将cur指向的节点的next指针指向pre,从而实现反转。
  3. precur分别指向curcurnext,继续遍历链表。
  4. 重复步骤2和步骤3,直到cur指向null,此时链表反转完成。

代码示例

class ListNode {
public:
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(nullptr) {}
};

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode *pre = nullptr, *cur = head;
        while (cur) {
            ListNode *next = cur->next;
            cur->next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
};
class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}

class Solution {
    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;
    }
}
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

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

运行结果

输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
输入:head = []
输出:[]
输入:head = [1]
输出:[1]

总结

《剑指offer24反转链表》是一次精彩的算法探索之旅,通过双指针迭代法,我们可以轻松实现链表的反转。希望这篇文章对您的学习有所帮助。如果您有任何问题或建议,欢迎随时提出。