1. 程式人生 > 實用技巧 >VMware Workstation 不可恢復錯誤:(vmui) Exception 0xc0000005(access violation) has occurred.

VMware Workstation 不可恢復錯誤:(vmui) Exception 0xc0000005(access violation) has occurred.

題目描述

給定一個連結串列,刪除連結串列的倒數第n個節點,並且返回連結串列的頭結點。

示例:
給定一個連結串列: 1->2->3->4->5, 和 n = 2.
當刪除了倒數第二個節點後,連結串列變為 1->2->3->5.

說明:
給定的 n保證是有效的。

解決思路

雙指標法解決,快指標先走n+1步,慢指標再走,當快指標走完時,刪除慢指標後一個節點即可。
注意考慮刪除的是頭結點的情況,用啞結點可以避免特殊處理!!!

/**
 * 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 dummyHead = new ListNode(0);
        dummyHead.next=head;
        ListNode fast=dummyHead,slow=dummyHead;
        while (n--!=0&&fast!=null) {
            fast=fast.next;
        }

        fast=fast.next;
        while (fast!=null) {
            fast=fast.next;
            slow=slow.next;
        }
        slow.next=slow.next.next;
        return dummyHead.next;
    }
}