19 删除链表的倒数第N个节点
19. 删除链表的倒数第 N 个结点 - 力扣(LeetCode)
两个指针,一个指向第一个节点,另外一个指向第n个节点,然后一直往后移动.
注意:快慢指针要指向虚拟头结点,否则如果长度为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) {
ListNode dummyNode = new ListNode(0);
dummyNode.next=head;
ListNode firstNode=dummyNode;
ListNode secondNode=dummyNode;
for (int i = 0; i <= n ; i++){
secondNode=secondNode.next;
}
while(secondNode!=null){
firstNode=firstNode.next;
secondNode=secondNode.next;
}
firstNode.next=firstNode.next.next;
return dummyNode.next;
}
}
面试题 02.07 链表相交
面试题 02.07. 链表相交 - 力扣(LeetCode)
求出两个链表长度,并且求出两个链表长度的差值,让两个链表末尾对齐
注意:让curA为最长链表的头,lenA为其长度,如果不是就交换一下
/**
* 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) {
ListNode curA=headA;
ListNode curB=headB;
int lenA=0,lenB=0;
while(curA!=null){
lenA++;
curA=curA.next;
}
while(curB!=null){
lenB++;
curB=curB.next;
}
curA=headA;
curB=headB;
//让curA为最长链表的头,lenA为其长度,如果不是就交换一下
if(lenB>lenA){
int tmplen=lenA;
lenA=lenB;
lenB=tmplen;
ListNode tmpNode=curA;
curA=curB;
curB=tmpNode;
}
int gap=lenA-lenB;
while(gap-->0){
curA=curA.next;
}
while(curA!=null){
if(curA==curB){
return curA;
}
curA=curA.next;
curB=curB.next;
}
return null;
}
}
142 环形链表II
142. Linked List Cycle II - 力扣(LeetCode)
使用快慢指针。
关键点有两个:1. 判断链表是否有环。2. 找到环的入口。(使用数学公式进行推算)
当n等于1的时候,x=z,意味着,从头结点和相遇位置同时出发一个指针,两个指针的相遇位置就是环形入口。
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode slow=head;
ListNode fast=head;
while(fast!=null&&fast.next!=null){
slow =slow.next;
fast=fast.next.next;
if(slow==fast){
ListNode index1=fast;
ListNode index2=head;
while(index1!=index2){
index1=index1.next;
index2=index2.next;
}
return index1;
}
}
return null;
}
}