给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
示例 1:

输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
示例 2:
输入:head = [1], n = 1
输出:[]
示例 3:
输入:head = [1,2], n = 1
输出:[1]
最容易理解的:
/**
* 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) {
if (head == null) return null;
// 先算一下一共有多少个节点
int count = 0;
ListNode p = head;
while (p != null) {
count ++;
p = p.next;
}
ListNode result = new ListNode(0, head);
// 算一下要移动多少步
int needMoveNum = count - n;
p = result;
while (needMoveNum > 0) {
p = p.next;
needMoveNum --;
}
// 操作
p.next = p.next.next;
// 结束
return result.next;
}
}
栈
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
Deque<ListNode> stack = new LinkedList<ListNode>();
ListNode result = new ListNode(0, head);
ListNode p = result;
while (p != null) {
stack.push(p);
p = p.next;
}
for (int i = 0; i < n; i++) {
stack.pop();
}
ListNode oper = stack.peek();
oper.next = oper.next.next;
return result.next;
}
}

浙公网安备 33010602011771号