24. 两两交换链表中的节点
(1)递归法
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: 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
(2)虚拟头部节点
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
d_head=ListNode(next=head)
cur=d_head
while cur.next and cur.next.next:
temp=cur.next
temp1=cur.next.next.next
cur.next=cur.next.next
cur.next.next=temp
temp.next=temp1
cur=cur.next.next
return d_head.next
19.删除链表的倒数第N个节点
双指针法
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
d_head=ListNode(next=head)
slow=fast=d_head
for i in range(n+1):
fast=fast.next
while fast:
fast=fast.next
slow=slow.next
slow.next=slow.next.next
return d_head.next
面试题 02.07. 链表相交
双指针法,求长度,同时出发
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: 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:
curA, curB = curB, curA
lenA, lenB = lenB, lenA
for _ in range(lenB - lenA):
curB = curB.next
while curA:
if curA == curB:
return curA
else:
curA = curA.next
curB = curB.next
return None
142.环形链表II
快慢指针法
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
slow,fast=head,head
while fast and fast.next:
slow=slow.next
fast=fast.next.next
if slow==fast:
slow=head
while slow!=fast:
slow=slow.next
fast=fast.next
return slow
return None
集合法,集合内不能有重复的元素
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
vi=set()
while head:
if head in vi:
return head
vi.add(head)
head=head.next
return None