LeetCode:M-19. Remove Nth Node From End of List

LeetCode鏈接


Given a linked list, remove the nth node from the end of list and return its head.

For example,

   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:
Given n will always be valid.
Try to do this in one pass.


1、正向遍歷n個node到k node 處,假設總共有 m 個node,則k到末尾爲 m-n 個

2、在分別從 head 和 k 處開始遍歷到,知道 k 處指針遍歷到末尾,則 head 處指針遍歷了 m-k 個node,且此時的node距離末尾爲 m-(m-n) = n,正好是倒數第n個數


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {     
        ListNode start = new ListNode(0);
        start.next = head;
        ListNode l1 = start;        
        ListNode l2 = start;
        for(int i=1; i<=n; i++){
            l2=l2.next;
        }
        while(l2.next!=null){
            l1 = l1.next;
            l2 = l2.next;
        }
        
        l1.next = l1.next.next;
        return start.next;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章