24. 两两交换链表中的节点
1、while prev.next and prev.next.next正确;while prev.next.next and prev.next报错。
2、用cur=prev.next, post = prev.next.next, 方便两两交换。
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head: return head
dummy = ListNode(-1)
dummy.next = head
prev = dummy
while prev.next and prev.next.next:
cur = prev.next
post = prev.next.next
### swap ###
cur.next = post.next
post.next = cur
prev.next = post
prev = prev.next.next
return dummy.next
19. 删除链表的倒数第 N 个结点
1、使用了快慢指针
2、快指针先根据n的数值进行移动
3、fast.next 为空为while跳出条件
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
dummy = ListNode(-1)
dummy.next = head
fast, slow = dummy, dummy
while n:
fast = fast.next
n -= 1
while fast.next:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return dummy.next
160.链表相交
考虑构建两个节点指针 A , B 分别指向两链表头节点 headA , headB ,做如下操作:
指针 A 先遍历完链表 headA ,再开始遍历链表 headB ,当走到 node 时,共走步数为:a + (b - c); a+(b−c)
指针 B 先遍历完链表 headB ,再开始遍历链表 headA ,当走到 node 时,共走步数为:b + (a - c); b+(a−c)
如下式所示,此时指针 A , B 重合,并有两种情况:
a + (b - c) = b + (a - c); a+(b−c)=b+(a−c)
若两链表 有 公共尾部 (即 c > 0c>0 ) :指针 A , B 同时指向第一个公共节点node 。
若两链表 无 公共尾部 (即 c = 0c=0 ) :指针 A , B 同时指向 nullnull 。
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
A = headA
B = headB
while A != B:
if A:
A = A.next
else:
A = headB
if B:
B = B.next
else:
B = headA
return A
简化写法:
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
A, B = headA, headB
while A != B:
A = A.next if A else headB
B = B.next if B else headA
return A
142.环形链表II
1、先判断链表里有没有环
2、再判断环的入口在哪里
3、while fast and fast.next, 为了一直在环形链表里遍历。
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
fast, slow = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
new_head = head
inter_node = slow
while new_head != inter_node:
new_head = new_head.next
inter_node = inter_node.next
return inter_node
return None```