代码随想录算法训练营第四天 | 链表题目 两两交换链表中的节点 删除链表的倒数第N个节点 链表相交 环形链表II
两两交换链表中的节点
涉及修改链表结构的题,定义一个虚拟头节点会更方便。
/*
* @lc app=leetcode.cn id=24 lang=java
*
* [24] 两两交换链表中的节点
*/
// @lc code=start
/**
* 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 = new ListNode();
ListNode cur = new ListNode();
dummy.next = head;
cur = dummy;
ListNode temp = new ListNode();
ListNode before = new ListNode();
ListNode after = new ListNode();
// temp = head.next;
while (cur.next != null && cur.next.next != null) {
before = cur.next.next;
after = cur.next;
temp = before.next;
cur.next = before;
before.next = after;
after.next = temp;
cur = after;
}
return dummy.next;
}
}
// @lc code=end
删除链表的倒数第N个节点
类似数组快慢指针做法
/*
* @lc app=leetcode.cn id=19 lang=java
*
* [19] 删除链表的倒数第 N 个结点
*/
// @lc code=start
/**
* 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) {
ListNode dummy = new ListNode();
dummy.next = head;
ListNode first = dummy;
ListNode second = head;
for (int i = 0; i < n - 1; i++) {
second = second.next;
}
while (second.next != null) {
second = second.next;
first = first.next;
}
first.next = first.next.next;
return dummy.next;
}
}
// @lc code=end
链表相交
先求出链表长度,求其差值,让长链表到剩余长度与短链表长度相等的节点,然后开始寻找相交节点
/*
* @lc app=leetcode.cn id=160 lang=java
*
* [160] 相交链表
*/
// @lc code=start
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode A = headA;
ListNode B = headB;
int length_A = 0;
int length_B = 0;
while (A.next != null) {
length_A++;
A = A.next;
}
while (B.next != null) {
length_B++;
B = B.next;
}
int dif = 0;
// System.out.printf("%d, %d", length_A, length_B);
ListNode long_ = new ListNode();
ListNode short_ = new ListNode();
if (length_A > length_B) {
long_ = headA;
short_ = headB;
dif = length_A - length_B;
} else {
long_ = headB;
short_ = headA;
dif = length_B - length_A;
}
for (int i = 0; i < dif; i++) {
long_ = long_.next;
}
while (long_ != null) {
if (long_ == short_) {
return long_;
}
long_ = long_.next;
short_ = short_.next;
}
return null;
}
}
// @lc code=end
环形链表II
本质是数学题,初见没有思路,也是采用快慢指针的做法,如果指针有相遇则存在环
还需要理解,如何找到入口的公式

浙公网安备 33010602011771号