两两交换链表节点(力扣24)
class Solution {
public ListNode swapPairs(ListNode head) {
//定义虚拟头部节点
ListNode dummyhead = new ListNode(-1);
dummyhead.next = head;
ListNode cur = dummyhead;
while(cur.next != null&& cur.next.next != null){
//定义两临时指针指向后两个节点
ListNode temp = cur.next;
ListNode temp2 = cur.next.next;
cur.next = temp2;
temp.next = temp2.next;
temp2.next = temp;
cur = cur.next.next;
}
return dummyhead.next;
}
}
删除倒数第N个节点(力扣19)
从题解中找到很巧妙的思路,利用双指针,让前指针先走n个节点,当前指针指向空时,后指针刚好走到目标节点的前驱;
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummyhead = new ListNode(-1);
dummyhead.next = head;
ListNode cur = dummyhead;
ListNode temp = dummyhead;
//采用双指针,使前指针快后指针n个即可
for(int i = 0; i < n; i++){
temp = temp.next;
}
while(temp.next != null){
temp = temp.next;
cur = cur.next;
}
cur.next = cur.next.next;
return dummyhead.next;
}
}
相交链表(力扣160)
这题只需要从长度相同的地方出发,依次对比节点是否相同即可找出
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode temp = headA;
ListNode temp2 = headB;
int size = 0, size2 = 0;
while(temp.next != null){
size++;
temp = temp.next;
}
while(temp2.next != null){
size2++;
temp2 = temp2.next;
}
if(size2 > size){
while(size2-size > 0){
headB = headB.next;
size2--;
}
}else{
while(size-size2 > 0){
headA = headA.next;
size--;
}
}
while(headA != null){
if(headA == headB){
return headA;
}
headA = headA.next;
headB = headB.next;
}
return null;
}
}
环形链表(力扣142)
这道题最难想的就是如何计算出入口节点;
解题思路:1.设置快慢指针,慢指针走一个节点,快指针走两个;当他们相遇时该链表存在环;
2.快慢指针相遇时,慢指针在环内移动距离必然小于环长,也就是慢指针走不满一圈(以最坏情况假设,慢指针进入环,快指针在慢指针下一个节点,那么快指针追上慢指针只需要环长-1就能追上)
3.由以上可知慢指针移到距离为:x+y;
快指针移动距离为:x+y+n(y+z);n为走了给n个环长;
因为快指针速度为慢指针两倍:2(x+y) = x+y+n(y+z);
所以:x-z = (n-1)(y+z);
由此可知,从头节点出发,走z个节点,剩下的节点数是环长的倍数;从相遇点出发走z个节点到达入口,再走n倍的环长依然在入口节点
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode temp = head;
ListNode temp2 = head;
while(temp2 != null && temp2.next != null){
temp = temp.next;
temp2 = temp2.next.next;
if(temp == temp2){
ListNode cur = head;
while(cur != temp){
temp = temp.next;
cur = cur.next;
}
return cur;
}
}
return null;
}
}