目录
学习目标
- 24. 两两交换链表中的节点
- 19.删除链表的倒数第N个节点
- 面试题 02.07. 链表相交
- 142.环形链表II
学习内容
24. 两两交换链表中的节点
24. 两两交换链表中的节点 - 力扣(LeetCode)
https://leetcode.cn/problems/swap-nodes-in-pairs/submissions/
递归
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head:return None
if not head.next:return head
last = self.swapPairs(head.next.next)
tmp = head.next
head.next = last
tmp.next = head
return tmp
迭代 利用虚拟头节点结合图像清晰每一步变化 明确每一个变量的含义 避免混淆
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head:return None
if not head.next:return head
dummyhead = ListNode(next = head)
first = dummyhead
middle = dummyhead.next
while middle and middle.next:
last = middle.next
first.next = last
tmp = last.next
last.next = middle
middle.next = tmp
first = middle
middle = tmp
return dummyhead.next
19.删除链表的倒数第N个节点
19. 删除链表的倒数第 N 个结点 - 力扣(LeetCode)
https://leetcode.cn/problems/remove-nth-node-from-end-of-list/利用快慢指针 形如一个追及问题
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
dummyhead = ListNode(next = head)
fast = head
slow = dummyhead
while n-1:
fast = fast.next
n-=1
while fast.next:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return dummyhead.next
面试题 02.07. 链表相交
面试题 02.07. 链表相交 - 力扣(LeetCode)
https://leetcode.cn/problems/intersection-of-two-linked-lists-lcci/
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
tmp1 = headA
tmp2 = headB
while tmp1!=tmp2:
if tmp1:
tmp1 = tmp1.next
else:
tmp1 = headB
if tmp2:
tmp2 = tmp2.next
else:
tmp2 = headA
return tmp1
142.环形链表II
142. 环形链表 II - 力扣(LeetCode)
https://leetcode.cn/problems/linked-list-cycle-ii/快慢指针 追及问题 套圈了啊
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
fast = head
slow = head
while fast != None and fast.next != None:
fast = fast.next.next
slow = slow.next
if slow==fast:
break
if fast == None or fast.next == None:return None
slow = head
while fast!=slow:
fast = fast.next
slow = slow.next
return fast