[Leetcode 19]删除链表中倒数第N个元素Remove Nth Node From End of List
题目
删除链表head中倒数第N个元素
Given the head
of a linked list, remove the nth
node from the end of the list and return its head.
Example 1:
Input: head = [1,2,3,4,5], n = 2 Output: [1,2,3,5]
Example 2:
Input: head = [1], n = 1 Output: []
Example 3:
Input: head = [1,2], n = 1 Output: [1]
题目分析
- 单向链表 -> 没有环
- 倒数,从后往前 -> 快慢指针,俩者始终间隔N,快指针走到头,慢指针反推即是倒数第N
- 需要删除节点,head头结点本身也可能被删除 -> new listnode辅助,next指向head,最后返回他的.next
- 已规定N必小于总长,即不会出现倒数第N不存在
代码
public ListNode removeNthFromEnd(ListNode head, int n) { ListNode tmp=new ListNode(-1); tmp.next=head; ListNode slow=tmp; ListNode fast=tmp; for(int i=0;i){ fast=fast.next; } while(fast.next!=null){ fast=fast.next; slow=slow.next; } slow.next=slow.next.next; return tmp.next;//不能直接head,head本身可能也被remove }