题目:给你一个链表,删除链表的倒数第 n
个结点,并且返回链表的头结点。
package com.test58_LeetCode;
public class E03LeetCode19 {
/* 方法1
recursion(ListNode p=1, int n=2) {
recursion(ListNode p=2, int n=2) {
recursion(ListNode p=3, int n=2) {
recursion(ListNode p=4, int n=2) {
recursion(ListNode p=5, int n=2) {
recursion(ListNode p=null, int n=2) {
return 0;
}
return 1;
}
return 2;
}
if(返回值 == n == 2) {
删除
}
return 3;
}
return 4;
}
return 5;
}
*/
//方法1
public ListNode removeNthFromEnd(ListNode head , int n){
//加哨兵,可以防止第一个元素(倒数最后一个元素)删除不掉。
//recursion递归是通过 p p上一个--->p下一个 节点,所以第一个节点没有上一个节点,所以会漏掉第一个节点
ListNode s = new ListNode(-1, head);
recursion(s,n);
return s.next;
}
private int recursion(ListNode p , int n){
if(p == null){
return 0;
}
int r = recursion(p.next, n);
if(r == n){
// 删除倒数节点,跳过该节点
p.next = p.next.next;
}
return r+1;
}
/*
n=2
p1
p2
s -> 1 -> 2 -> 3 -> 4 -> 5 -> null
p2
s -> 1 -> 2 -> 3 -> 4 -> 5 -> null
p2
s -> 1 -> 2 -> 3 -> 4 -> 5 -> null
p1 p2
s -> 1 -> 2 -> 3 -> 4 -> 5 -> null
p1 p2
s -> 1 -> 2 -> 3 -> 4 -> 5 -> null
*/
//方法2
public ListNode removeNthFromEnd2(ListNode head , int n){
ListNode s = new ListNode(-1,head);
ListNode p1 =s;
ListNode p2 =s;
for (int i = 0 ; i < n + 1 ; i++){
p2 = p2.next;
}
while (p2 != null){
p1 = p1.next;
p2 = p2.next;
}
p1.next = p1.next.next;
return s.next;
}
public static void main(String[] args) {
ListNode list = ListNode.of(1, 2, 3, 4, 5);
ListNode head = new E03LeetCode19().removeNthFromEnd2(list, 2);
System.out.println(head);
}
}