day04 | LeetCode24. 两两交换链表中的节点、19.删除链表的倒数第N个节点、142.环形链表II
创建时间: October 16, 2022 8:58 PM
一、今日任务
-
- 两两交换链表中的节点
- 2
- 3
二、具体实现
24. 两两交换链表中的节点
学习链接
思路
d→1→2→4→5→6
,进行交换的顺序是:
- d→2
- 2→1
- 1→4
这里需要注意的是,在交换的时,用临时变量保存指针,防止指针的丢失。
这道题要明确是 循环的边界 和 交换的逻辑。
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode();
ListNode temp = new ListNode();
ListNode temp1 = new ListNode();
dummy.next = head;
ListNode cur = dummy;
// 奇数 cur.next.next != null
// 偶数 cur.next != null
while(cur.next != null && cur.next.next != null){
temp = cur.next;
temp1 = cur.next.next.next;
// 指针交换
cur.next = cur.next.next;
cur.next.next = temp;
temp.next = temp1;
// current 往后移动两位
cur = cur.next.next;
}
return dummy.next;
}
}
19.删除链表的倒数第N个节点
学习链接
解题
双指针经典题型,先让fast
指针移动n+1
后,fast
和slow
指针在同时移动,fast
指针移动到null
结束,这时slow
指针移动了要删除的节点前面一位,执行正常的删除流程。移动n+1
位是为了让slow
指针指向要删除的节点前一位。
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode();
dummy.next = head;
ListNode fast = dummy;
ListNode slow = dummy;
n++;
while(n-- > 0 && fast != null){
fast = fast.next;
}
while(fast != null){
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return dummy.next;
}
}
142.环形链表II
学习链接
解题
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
ListNode index1 = new ListNode();
ListNode index2 = new ListNode();
// 快指针每次移动两个节点
// 慢指针每次移动一个节点
while(fast!=null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
// 快慢指针相遇
if (fast == slow){
index1 = fast;
index2 = head;
while(index1 != index2){
index1 = index1.next;
index2 = index2.next;
}
return index1;
}
}
return null;
}
}