LeetCode24 交换链表节点
public class code24 {
public ListNode swapPairs(ListNode head) {
ListNode dummyhead = new ListNode(0);
dummyhead.next = head;
ListNode cur = dummyhead;
ListNode temp1 = null;
ListNode temp2 = null;
while (cur.next != null && cur.next.next != null) {
// 两个临时节点防止过程中链表断开
temp1 = cur.next;
temp2 = cur.next.next.next;
// 交换
cur.next = cur.next.next;
cur.next.next = temp1;
temp1.next = temp2;
cur = cur.next.next;
}
return dummyhead.next;
}
注意链表操作时不要让链表断开
LeetCode19 删除倒数第N个节点
public class code19 {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummynode = new ListNode(0);
dummynode.next = head;
ListNode fast = dummynode;
ListNode slow = dummynode;
for (int i = 0; i < n + 1; i++) {
fast = fast.next;
}
while (fast != null) {
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return dummynode.next;
}
}
快指针先移动n+1位置,之后一起移动,当快指针指向空指针的时候,慢指针指向倒数第n+1个元素,然后就可以删除倒数第n个元素,画图模拟一下很清晰
LeetCode160 链表相交
public class code02_07 {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode p1 = headA;
ListNode p2 = headB;
while (p1 != p2) {
if (p1 == null) {
p1 = headB;
} else {
p1 = p1.next;
}
if (p2 == null) {
p2 = headA;
} else {
p2 = p2.next;
}
}
return p1;
}
}
两个指针最终走过的路程相等,如果有相同节点就会相遇
LeetCode142 环形链表
题目链接:https://programmercarl.com/0142.%E7%8E%AF%E5%BD%A2%E9%93%BE%E8%A1%A8II.html代码如下:
// 环形链表,主要是数学原理搞清楚
public class code142 {
public ListNode detectCycle(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
if (fast == slow) {
ListNode index1 = fast;
ListNode index2 = head;
while (index1 != index2) {
index1 = index1.next;
index2 = index2.next;
}
return index1;
}
}
return null;
}
}
文章讲的很详细,搞清楚原理写代码就很简单了