203. 移除链表元素
/**
* 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 removeElements(ListNode head, int val) {
//循环删除值相同的头结点
while(head != null && head.val == val) {
head=head.next;
}
if(head == null)
return head;
ListNode tmp = head;
while(tmp.next != null){
if(tmp.next.val == val){
tmp.next = tmp.next.next;
}else {
tmp = tmp.next;
}
}
return head;
}
}
206. 反转链表
解题思路
类似双指针算法
视频思路
/**
* 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 reverseList(ListNode head) {
ListNode cur = head;
ListNode pre = null;
ListNode tmp = null;
while(cur != null) {
tmp = cur.next;
cur.next = pre ;
pre = cur;
cur = tmp;
}
return pre;
}
}
两两交换链表中的节点
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummyNode = new ListNode(0);
dummyNode.next = head;
ListNode prev = dummyNode;
while (prev.next != null && prev.next.next != null) {
ListNode temp = head.next.next; // 缓存 next
prev.next = head.next; // 将 prev 的 next 改为 head 的 next
head.next.next = head; // 将 head.next(prev.next) 的next,指向 head
head.next = temp; // 将head 的 next 接上缓存的temp
prev = head; // 步进1位
head = head.next; // 步进1位
}
return dummyNode.next;
}
}
删除链表的倒数第 N 个结点
注意好三个指针的关系
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode slow = dummy;
ListNode fast = dummy;
while (n-- > 0) {
fast = fast.next;
}
// 记住 待删除节点slow 的上一节点
ListNode prev = null;
while (fast != null) {
prev = slow;
slow = slow.next;
fast = fast.next;
}
// 上一节点的next指针绕过 待删除节点slow 直接指向slow的下一节点
prev.next = slow.next;
// 释放 待删除节点slow 的next指针, 这句删掉也能AC
slow.next = null;
return dummy.next;
}
}
链表相交
假设a是headA不相交部分,b是headB不相交部分, c是两者相交部分 a + c + b +c = b + c + a + c 假设headA和headB不相交 a + b = b + a 最后一定共同停在空指针位置
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode A = headA, B = headB;
while (A != B) {
A = A != null ? A.next : headB;
B = B != null ? B.next : headA;
}
return A;
}
}
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 = fast;
ListNode index2 = head;
// 两个指针,从头结点和相遇结点,各走一步,直到相遇,相遇点即为环入口
while (index1 != index2) {
//关键点:这就是这题的巧妙之处,也是本体的规律
index1 = index1.next;
index2 = index2.next;
}
return index1;
}
}
return null;
}
}
这篇博客涵盖了多种链表操作的解题思路和算法实现,包括移除链表元素、反转链表、两两交换链表中的节点、删除链表的倒数第N个结点、寻找链表相交节点和检测环形链表。每个问题都提供了详细的代码示例,解析了如何高效地处理链表结构中的各种操作。
281

被折叠的 条评论
为什么被折叠?



