24. 两两交换链表中的节点
题目描述:给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
思路:1.迭代法 2.递归 (运用递归函数)
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
node0=dummy=ListNode(next=head)
node1=head
while node1 and node1.next:
node2=node1.next
node3=node2.next
node0.next=node2
node2.next=node1
node1.next=node3
node0=node1
node1=node3
return dummy.next
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head is None or head.next is None:
return head
pre=head
cur=head.next
next=head.next.next
cur.next=pre
pre.next=self.swapPairs(next)
return cur
题目描述:给你一个链表,删除链表的倒数第 n
个结点,并且返回链表的头结点。
思路:1.首先想到迭代法 ,找到第length-n个结点,删除。
2.双指针法,运用快慢指针,如果要删除倒数第n个节点,让fast移动n步,然后让fast和slow同时移动,直到fast指向链表末尾。删掉slow所指向的节点就可以了。
要注意的是,要先让fast走n+1步。
-
因为只有这样同时移动的时候slow才能指向删除节点的上一个节点(方便做删除操作),如图:
-
fast和slow同时移动,直到fast指向末尾,如题:
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
dummy_head=ListNode(next=head)
cur=dummy_head.next
length=0
while cur:
length+=1
cur=cur.next
pre=dummy_head
for i in range(length-n):
pre=pre.next
pre.next= pre.next.next
return dummy_head.next
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
dummy_head=ListNode(next=head)
slow=fast=dummy_head
for i in range(n+1):
fast=fast.next
while fast:
slow=slow.next
fast=fast.next
slow.next=slow.next.next
return dummy_head.next
相比于迭代法,双指针法更简便
题目描述:
给你两个单链表的头节点 headA
和 headB
,请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null
。
图示两个链表在节点 c1
开始相交:
题目数据 保证 整个链式结构中不存在环。
注意,函数返回结果后,链表必须 保持其原始结构 。
思路:先求出链表A,B的长度,然后求他们之间的差,再遍历到差的位置,然后判断后面长短链表的每一个节点是否相等。
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
lenA,lenB=0,0
cur=headA
while cur:
cur=cur.next
lenA+=1
cur=headB
while cur:
cur=cur.next
lenB+=1
curA,curB=headA,headB
if lenA > lenB:
for _ in range(lenA - lenB):
curA = curA.next
else:
for _ in range(lenB - lenA):
curB = curB.next
while curA != curB:
curA = curA.next
curB = curB.next
return curA
题目:
给定一个链表的头节点 head
,返回链表开始入环的第一个节点。 如果链表无环,则返回 null
。
如果链表中有某个节点,可以通过连续跟踪 next
指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数 pos
来表示链表尾连接到链表中的位置(索引从 0 开始)。如果 pos
是 -1
,则在该链表中没有环。注意:pos
不作为参数进行传递,仅仅是为了标识链表的实际情况。
不允许修改 链表。
思路:设置快指针每次走两个节点,慢指针每次走一个节点,所以快指针是慢指针的两倍,slow=x+y fast=x+y+n(y+z) 能写出这些公式:2(x+y)=x+y+n(y+z) 化简得出x的相关式子为x=(n-1)(y+z)+z 可以看出x=z 当两个指针相遇,此时慢指针从头指针开始 与快指针一起运动,直到在环形链表入口再次相遇。
class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
slow,fast=head,head
while fast and fast.next:
fast=fast.next.next
slow=slow.next
if slow==fast:
slow=head
while slow!=fast:
slow=slow.next
fast=fast.next
return slow
return None