题目
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
示例 2:
输入:head = [1], n = 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) {
List<ListNode> list = new ArrayList<>();
ListNode cur = head;
int size = 0;
while (cur != null){
list.add(cur);
cur = cur.next;
size++;
}
//统计完成
if (size == n) return head.next;//这等价于删除头结点
if (size == 1) head = null;//只有一个头结点
else list.get(size - n - 1).next = list.get(size - n - 1).next.next;//剩下的删除都换
return head;
}
}