LeetCode19- 刪除鏈表的倒數第N個節點

給定一個鏈表,刪除鏈表的倒數第 個節點,並且返回鏈表的頭結點。

示例:

給定一個鏈表: 1->2->3->4->5, 和 n = 2.

當刪除了倒數第二個節點後,鏈表變爲 1->2->3->5.

說明:

給定的 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) {
        if ( n <= 0 ) {
            return head;
        }
        ListNode p = head;
        ListNode q = new ListNode(0);
        q.next = head;
        int i = 1 , j = 1;
        while( p.next != null ) {
            if ( i < n ) {
                p = p.next;
                i++;
                if ( p.next == null ) {
                    return head.next;
                }
            }
            else {
                p = p.next;
                q = q.next;
                j++;
            }
        }
        if ( i != 1 && j == 1 ) {
            return head;
        }
        else if ( i == 1 && j == 1 ) {
            return head.next;
        }
        else {
            q.next = q.next.next;
            return head;
        }
        
    }
}

運行結果:

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