lintcode 关于链表快慢指针

本文深入解析链表算法,涵盖倒数第k个节点、链表判环、找环入口及链表重排等核心问题。通过具体实例,提供Python实现代码,帮助读者掌握链表操作的关键技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

倒数第k个节点:O(N)时间复杂度O(1)空间复杂度

假设当前链表的长度m,要求倒数第k个链表结点

①首先建立两个指针引用,分别为slow,fast。一开始都为head头结点

②fast指针移动k-1次,此时fast指针位于链表的第k个结点位置处。

③fast与slow指针同时向后移动,当fast指针指向链表末尾时,slow指针位于链表倒数第k个位置处。

lintcode 166

class Solution:
    """
    @param: head: The first node of linked list.
    @param: n: An integer
    @return: Nth to last node of a singly linked list. 
    """
    
    def nthToLast(self, head, n):
        # write your code here
        if head is None or n < 1:
            return None
        length = head
        num = 1
        while length.next:
            length = length.next
            num += 1 
        if n > num:
            return None
        slow = head
        for i in range(n):
            head = head.next
        while head:
            head = head.next
            slow = slow.next
        return slow

链表判环:

快慢指针起点相同,快指针移动速度是慢指针两倍,当快指针与慢指针相遇的时候说明此链表有环,否则没环.

lintcode 102

class Solution:
    """
    @param head: The first node of linked list.
    @return: True if it has a cycle, or false
    """
    def hasCycle(self, head):
        # write your code here
        if head is None:
            return False
        slow,fast = head,head
        while True:
            if fast.next:
                slow = slow.next
                fast = fast.next.next
                if slow is None or fast is None:
                    return False
                elif slow == fast:
                    return True
                
            else:
                return False
        return False

找环入口:

①fast指针先行每次移动两步,slow指针后行每次移动一步,直到fast指针追上slow指针,进入②;

②slow指针从头开始往下每次移动一步,同时从第一个fast指针每次也移动一步,直到slow指针追上fast指针,该节点就是环的入口节点。

lintcode 103

class Solution:
    """
    @param head: The first node of linked list.
    @return: The node where the cycle begins. if there is no cycle, return null
    """
    def detectCycle(self, head):
        # write your code here
        if head is None or head.next is None:
            return None
        slow,fast = head, head
        dummy = head.next.next
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            if fast == slow:
                slow = head
                while slow != fast:
                    slow = slow.next
                    fast = fast.next
                return slow

链表重排:

lintcode 99

通过快慢指针,找到链表的中点,从中点的下一个节点开始,逆序后面的链表,注意需要在链表断开处将中点节点的next指针置NULL。逆序之后,在顺序插入到前面的链表中。终止条件:两个链表中一个到达末尾。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值