Day3+Day4 Linked List链表
Q24 Swap Nodes
[Q24]
def swapPairs(self, head: ListNode) -> ListNode:
res = ListNode(next=head) # 停在dummy_head
pre = res
# 必须有pre的下一个和下下个才能交换,否则说明已经交换结束了
while pre.next and pre.next.next:
cur = pre.next # cur@1
post = pre.next.next # post@2
# pre, cur, post对应最左边,中间,最右边的节点
cur.next = post.next # 1-->3
post.next = cur # 2-->1
pre.next = post # pre-->2
pre = pre.next.next # pre@1, [2,1,3,4]
return res.next
var swapPairs = function (head) {
let ret = new ListNode(0, head), temp = ret;
while (temp.next && temp.next.next) {
let cur = temp.next.next, pre = temp.next;
pre.next = cur.next;
cur.next = pre;
temp.next = cur;
temp = pre;
}
return ret.next;
};
Q19 Remove Nth From End
[Q19]
Input: 1-->2-->3-->4-->5 , remove the n=2 node from the end
Output: 1-->2-->3-->5
Logic: 双指针,如果要删除倒数第n个节点,让fast移动n步,然后让fast和slow同时移动,直到fast指向链表末尾。删掉slow所指向的节点就可以了
Set fast & slow at dummy_head initially
fast walk n+1 steps firstly, now fast@3
fast & slow walk simultaneously until fast @NULL, now slow@3, modify slow.next = 5
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
dummy_head = ListNode()
dummy_head.next = head
slow, fast = dummy_head, dummy_head
while(n!=0): # fast walk n steps firstly
fast = fast.next
n -= 1
while(fast.next != None):
slow = slow.next
fast = fast.next
# fast walks to tail, slow.nexr should be the Nth Node from end
slow.next = slow.next.next
return dummy_head.next
var removeNthFromEnd = function(head, n) {
let ret = new ListNode(0, head),
slow = fast = ret;
while(n--) fast = fast.next;
while (fast.next !== null) {
fast = fast.next;
slow = slow.next
};
slow.next = slow.next.next;
return ret.next;
};
Q160 Intersection
[Q160]
A1-->a2--------->c1-->c2-->c3
B1-->b2-->b3-->c1-->c2-->c3
Logic:
目前curA指向链表A的头结点,curB指向链表B的头结点
求出两个链表的长度,并求出两个链表长度的差值,然后让curA移动到,和curB 末尾对齐的位置
此时我们就可以比较curA和curB是否相同,如果不相同,同时向后移动curA和curB,如果遇到curA == curB,则找到交点, 否则循环退出返回空指针
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
lenA, lenB = 0,0
cur = headA
while cur: # 链表A的长度
cur = cur.next
lenA += 1
cur = headB
while cur: # 链表B的长度
cur = cur.next
lenB += 1
curA, curB = headA, headB
if lenA > lenB: # 让curB为较长链表的头, lenB为其长度
curA, curB = curB, curA
lenA, lenB = lenB, lenA
for _ in range(lenB-lenA): # 让curA和curB在同一起点(末尾位置对齐)
curB = curB.next
while curA: # 遍历curA & curB, 遇到相同就直接返回
if curA == curB:
return curA
else:
curA = curA.next
curB = curB.next
return None
Q142 Linked List Cycle (代码随想录)
[Q142]
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
slow, fast = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
# 如果相遇
if slow == fast:
p = head
q = slow
while p!=q:
p = p.next
q = q.next
#你也可以return q
return p
return None
Reference: https://programmercarl.com/