题目
给你一个链表,删除链表的倒数第
n
个结点,并且返回链表的头结点。
注意
- 创建链表:ListNode list = new ListNode(0, head);
代码
/**
* 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 list = new ListNode(0, head);
ListNode p = list;
ListNode q = list;
for (int i = 0; i < n; i++) {
p = p.next;
}
while (p.next != null) {
p = p.next;
q = q.next;
}
q.next = q.next.next;
ListNode node = list.next;
return node;
}
}