24. 两两交换链表中的节点
24. 两两交换链表中的节点https://leetcode.cn/problems/swap-nodes-in-pairs/
应用虚拟节点,virtualHead,
cur、one (1)、two (2)、temp(cur.next.next.next)节点,分别进行节点的两两交换
整体思路是这样的
依次遍历
19. 删除链表的倒数第 N 个结点
19. 删除链表的倒数第 N 个结点https://leetcode.cn/problems/remove-nth-node-from-end-of-list/
思路:
虚拟头节点,快慢指针,慢指针指向倒数第n+1个节点,
删除的时候,需要删除的节点 的前序节点指向 后置节点
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head==null){
return head;
}
ListNode virtualHead=new ListNode(-1,head);
ListNode fast=virtualHead;
ListNode slow=virtualHead;
for(int i=0;i<=n;i++){
fast=fast.next;
}
while(fast!=null){
fast=fast.next;
slow=slow.next;
}
slow.next=slow.next.next;
return virtualHead.next;
}
面试题 02.07. 链表相交
面试题 02.07. 链表相交https://leetcode.cn/problems/intersection-of-two-linked-lists-lcci/
思路是快慢指针,先分别计算长度,按差值进行快慢指针遍历,循环中如果有相等的,直接退出,否则无相交节点
for(int i=0;i<lA-lB;i++){
curA=curA.next;
}
while(curA!=null){
if(curA==curB){
return curA;
}
curA=curA.next;
curB=curB.next;
}
142. 环形链表 II
142. 环形链表 IIhttps://leetcode.cn/problems/linked-list-cycle-ii/
快慢指针,依次遍历,
先死循环,fast一次2步,slow一次1步,得出第一次相遇的节点,如果无环,fast和fast.next可能为空,
相遇之后,fast返回头节点,重新追赶,再次相遇的地点一定是环的入口,因为都是一次1步走的,必定在环入口处相遇
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode slow=head,fast=head;
while(true){
if(fast==null || fast.next==null) return null;
fast=fast.next.next;
slow=slow.next;
if(fast==slow)break;
}
fast=head;
while(slow!=fast){
slow=slow.next;
fast=fast.next;
}
return fast;
}
}