一、24. 两两交换链表中的节点
1.原题
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummyNode = new ListNode(0);
dummyNode.next = head;
ListNode pre = dummyNode;
while(dummyNode.next != null && dummyNode.next.next != null){
ListNode temp = dummyNode.next;
dummyNode.next = dummyNode.next.next;
temp.next = dummyNode.next.next;
dummyNode.next.next = temp;
dummyNode = temp;
}
return pre.next;
// ListNode dummyNode = new ListNode(0);
// dummyNode.next = head;
// ListNode pre = dummyNode;
// while(pre.next != null && pre.next.next != null){
// ListNode temp = pre.next;
// ListNode temp1 = pre.next.next.next;
// pre.next = pre.next.next;
// pre.next.next = temp;
// pre.next.next.next = temp1;
// pre = pre.next.next;
// }
// return dummyNode.next;
}
}
两种写法思路基本相同,无难度
二、19.删除链表的倒数第N个节点
1.原题
ListNode nummyhead = new ListNode(-1);
nummyhead.next = head;
ListNode show = nummyhead;
ListNode fast = nummyhead;
while (n + 1 > 0){
fast = fast.next;
n--;
}
while(fast != null){
fast = fast.next;
show = show.next;
}
show.next = show.next.next;
return nummyhead.next;
}
此题思路,快慢指针,想让快指针走N+1步,这里的n+1步的原因是让慢指针和快指针之间有n个结点,
如此一来,当快指针为null的时候,慢指针后面恰好剩n个结点,删除倒数第n个,刚好show.next = show.next.next;
三、面试题 02.07. 链表相交
1原题
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode curA = headA;
ListNode curB = headB;
int lenA = 0,lenB = 0;
while(curA != null){
curA = curA.next;
lenA++;
}
while(curB != null){
curB = curB.next;
lenB++;
}
curA = headA;
curB = headB;
if(lenB > lenA){
ListNode temp = curA;
curA = curB;
curB = temp;
int k = lenA;
lenA = lenB;
lenB = k;
}
int m = lenA - lenB;
while(m-- > 0){
curA = curA.next;
}
while(curB != null && curA != null){
if(curA == curB){
return curA;
}
curA = curA.next;
curB = curB.next;
}
return null;
}
}
思路
:先循环一遍记录两个链表长度,再让curA指向较长的那条链表,让curA先移动两条链表的差值(就是让两个链表同时走到结尾,长链表长出来那部分需要先忽略掉),然后同时移动,判断是否相等。
四、142.环形链表II
1.原题
难点
public class Solution {
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;
}
}
思路
:快慢指针, 快指正一次走两步,慢指正一次走一步,如果有环,快慢指针必会相等;
环链表入口
: 此题的最难点,根据数学公式推算,两个指针一个从相遇的点开始移动,一个从头结点开始移动,两结点相遇的地方就是环链表的入口。