24. 两两交换链表中的节点
/**
* 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) {
//使用双指针+虚拟头结点的方法亮亮交换链表中的节点
//注意:画图确定交换的顺序
ListNode dummy = new ListNode();
dummy.next = head;
ListNode cur = dummy;
while(cur.next != null && cur.next.next !=null){
ListNode tmp = cur.next;
ListNode tmp1 = cur.next.next.next;
//开始交换
cur.next = cur.next.next;
cur.next.next = tmp;
tmp.next.next.next = tmp1;
//准备开始下一组交换
cur = cur.next.next;
}
return dummy.next;
}
}
19.删除链表的倒数第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) {
//链表中双指针的经典应用,快慢指针,先让快指针fast 移动n步,再将slow和fast同时移动,直到fast指向Null
//首先创建虚拟头节点
ListNode dummy = new ListNode();
dummy.next = head;
ListNode slow = dummy;
ListNode fast = dummy;
for(int i = 0;i < n; i++){
fast = fast.next;
}
//此处fast节点移动n+1次,可以保证当fast移动到最后null时候,slow刚好指向待删除节点的前一个节点,方便了删除的过程
fast = fast.next;
while(fast != null){
slow = slow.next;
fast = fast.next;
}
//此时slow指向待删除节点的前一个节点
slow.next = slow.next.next;
return dummy.next;
}
}
160. 相交链表
/**
* 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) {
// p1 指向 A 链表头结点,p2 指向 B 链表头结点
ListNode p1 = headA, p2 = headB;
while (p1 != p2) {
// p1 走一步,如果走到 A 链表末尾,转到 B 链表
if (p1 == null) p1 = headB;
else p1 = p1.next;
// p2 走一步,如果走到 B 链表末尾,转到 A 链表
if (p2 == null) p2 = headA;
else p2 = p2.next;
}
return p1;
}
}
142. 环形链表 II
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
ListNode detectCycle(ListNode head) {
ListNode fast, slow;
fast = slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
if (fast == slow) break;
}
// 上面的代码类似 hasCycle 函数
if (fast == null || fast.next == null) {
// fast 遇到空指针说明没有环
return null;
}
// 重新指向头结点
slow = head;
// 快慢指针同步前进,相交点就是环起点
while (slow != fast) {
fast = fast.next;
slow = slow.next;
}
return slow;
}
}
版权声明:本文为Fxxkke原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。