19. 刪除鏈表的倒數第 n 個節點 Leetcode Java

//給定一個鏈表,刪除鏈表的倒數第 n 個節點,並且返回鏈表的頭結點。 
//
// 示例: 
//
// 給定一個鏈表: 1->2->3->4->5, 和 n = 2.
//
//當刪除了倒數第二個節點後,鏈表變爲 1->2->3->5.
// 
//
// 說明: 
//
// 給定的 n 保證是有效的。 
//
// 進階: 
//
// 你能嘗試使用一趟掃描實現嗎? 
// Related Topics 鏈表 雙指針


//leetcode submit region begin(Prohibit modification and deletion)

/**
 * 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 pre = new ListNode(0);
        pre.next = head;
        ListNode fast, slow;
        fast = slow = pre;
        while (n-- >= 0) {
            //如果n-->=0 slow是倒數第k+1個元素
            //如果n-->0 slow 是倒數第k個元素
            fast = fast.next;
        }
        while (fast != null) {
            fast = fast.next;
            slow = slow.next;
        }

        //刪掉倒數第K個元素
        System.out.println(slow.val);
        slow.next = slow.next.next;
        return pre.next;
    }

}
//leetcode submit region end(Prohibit modification and deletion)

 

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