题解 | #删除链表的倒数第n个节点#
删除链表的倒数第n个节点
https://www.nowcoder.com/practice/f95dcdafbde44b22a6d741baf71653f6
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @param n int整型
* @return ListNode类
*/
public ListNode removeNthFromEnd (ListNode head, int n) {
// write code here
ListNode newHead = new ListNode(-1);
ListNode tail = head;
newHead.next = head;
ListNode pre = newHead;
while (n != 1) {
tail = tail.next;
n--;
}
ListNode cur = head;
while (tail.next != null) {
cur = cur.next;
pre = pre.next;
tail = tail.next;
}
pre.next = cur.next;
cur.next = null;
return newHead.next;
}
}
迅雷公司福利 193人发布