代码随想录算法训练营第4天 | 24. 两两交换链表中的节点、19.删除链表的倒数第N个节点、面试题 02.07. 链表相交、142.环形链表II
24. 两两交换链表中的节点
题目:24. 两两交换链表中的节点
文档讲解:代码随想录-24. 两两交换链表中的节点
视频讲解:哔哩哔哩-24. 两两交换链表中的节点
状态/时间:没写出来/二十分钟
思路:
操作之后,链表如下:
24.两两交换链表中的节点2
看这个可能就更直观一些了:
这道题要画图才好做,不然会很懵。
代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode dummy_head = new ListNode(0);
dummy_head.next = head;
ListNode cur = dummy_head;
ListNode firstNode;
ListNode secondNode;
ListNode temp;
while (cur.next != null && cur.next.next != null) {
firstNode = cur.next;
secondNode = cur.next.next;
temp = cur.next.next.next;
cur.next = secondNode;
secondNode.next = firstNode;
firstNode.next = temp;
cur = firstNode;
}
return dummy_head.next;
}
}
注意:
1.不像c/c++那样可以直接写cur.next.next这种,在java里面必须把用到的结点要用变量保存下来先
19.删除链表的倒数第N个节点
题目:19.删除链表的倒数第N个节点
文档讲解:代码随想录-19.删除链表的倒数第N个节点
视频讲解:哔哩哔哩-19.删除链表的倒数第N个节点
状态/时间:没写出来/二十分钟
思路:
快指针跑的比慢指针快n步,然后快慢指针一起走,最后快指针的下一个为空时,就停着。
slow.next = slow.next.next就把倒数n个位置的结点给删了
代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if (head == null) {
return head;
}
// 虚拟头结点
ListNode dummy_head = new ListNode(0);
dummy_head.next = head;
ListNode slow = dummy_head;
ListNode fast = dummy_head;
// n++;
// while (n-- > 0 && fast != null) {
// fast = fast.next;
// }
for (int i = 0; i <= n; i++) {
fast = fast.next;
}
while (fast != null) {
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return dummy_head.next;
}
}
注意:
最终返回dummy_head.next
面试题 02.07. 链表相交
题目:面试题 02.07. 链表相交
文档讲解:代码随想录-面试题 02.07. 链表相交
视频讲解:哔哩哔哩-面试题 02.07. 链表相交(无视频)
状态/时间:没写出来/二十分钟
思路:
明天补
代码:
注意:
142.环形链表II
题目:142.环形链表II
文档讲解:代码随想录-142.环形链表II
视频讲解:哔哩哔哩-142.环形链表II
状态/时间:写出来了/十分钟(看完卡哥讲解视频后)
思路:
快指针快于慢指针一步,也就是快指针走2步,慢指针走1步,但是他们一定会相遇。这就好比,你跑步跑的慢, 你朋友跑的比你快,跑的路就如上图所示,他跑的快了,就要一直围绕着操场跑了,然后你慢慢跑,但是你们最后也是会相遇的。
相遇了说明,起点跟你们遇到的距离是相等的,具体可以看代码随想录的证明,然后就可以利用这个特性来解题。(虽然我也还是懵懵的)
代码:
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
ListNode index1 = head;
ListNode index2 = fast;
while (index1 != index2) {
index1 = index1.next;
index2 = index2.next;
}
return index1;
}
}
return null;
}
}
注意:
暂无