More:【目錄】LeetCode Java實現html
https://leetcode.com/problems/remove-nth-node-from-end-of-list/java
Given a linked list, remove the n-th node from the end of list and return its head.node
Example:post
Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:ui
Given n will always be valid.this
Follow up:spa
Could you do this in one pass?code
Using a dummyHead.htm
public ListNode removeNthFromEnd(ListNode head, int n) { ListNode dummy = new ListNode(0); dummy.next = head; ListNode n0 = head; ListNode n1 = head; ListNode pre = dummy; for(int i=0; i<n-1; i++) n1=n1.next; while(n1.next!=null){ n0=n0.next; n1=n1.next; pre=pre.next; } pre.next = n0.next; return dummy.next; //not head }
Time complexity : O(n)
blog
Space complexity : O(1)
More:【目錄】LeetCode Java實現