19. 删除链表的倒数第 N 个结点 - 力扣(LeetCode)
/**
* 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 pre=new ListNode(0);
pre.next=head;
ListNode start =pre;
ListNode end=pre;
while(n!=0){
start=start.next;
n--;
}
while(start.next!=null){
start=start.next;
end=end.next;
}
end.next=end.next.next;
return pre.next;
}
}
回到家了,开始疯狂补欠下的。
删除链表里的结点是学校里老师讲的重点了。
面试题 02.07. 链表相交 - 力扣(LeetCode)
/**
* 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 A=headA;
ListNode B=headB;
while(A!=B){
A=A!=null?A.next:headB;
B=B!=null?B.next:headA;
}
return A;
}
}
这个题之前在洛谷里做过类似的,用双指针方法好理解一些。
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode fast=head;
ListNode slow=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;
}
}
这题用快慢指针,关键在于推出fast=slow+nb(环的结点数)。