倒数第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。逆序之后,在顺序插入到前面的链表中。终止条件:两个链表中一个到达末尾。