给你一个链表,删除链表的倒数第 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]
提示:
链表中结点的数目为 sz
1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz
题解:快慢指针,slow和fast相差n个,
易错点:要设立一个头节点,防止删除的是第一个元素,不设立头节点的话,当要删除的是第 (链表.length) 个节点就不行。
/**
* 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 dummy = new ListNode(0,null);
dummy.next = head;
ListNode slow = dummy;
ListNode fast = head;
//将slow与fast距离相差有n个,
//当fast指向链表最后为空时,slow指向目标删除元素的前一个
//然后进行删除操作
for(int i = 0; i < n ; i++ )
{
fast = fast.next;
}
while(fast!= null)
{
slow = slow.next;
fast = fast.next;
}
slow.next = slow.next.next;
ListNode ans = dummy.next;
return ans;
}
}