Leetcode Remove Nth Node From End of List

OpenSoucre發表於2014-03-27

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.

題意轉換一下就是求解單連結串列的倒數第k個節點,解法是設定兩個指標,一個在前一個在後,之間的距離為k,同時向前移動,有點類似滑動視窗,當第一個指標到達連結串列尾的時候,第二個指標即為倒數第k個節點,具體的見程式設計之美

ListNode *removeNthFromEnd(ListNode *head, int n){
    if(head == NULL) return NULL;
    ListNode *q = head,*p = head;
    for(int i = 0 ; i < n - 1; ++ i)
        q = q -> next;
    ListNode *pPre = NULL;
    while(q->next){
        pPre = p;
        p = p->next;
        q = q->next;
    }
    if(pPre == NULL){
        pPre = p->next;
        delete p;
    }else{
        pPre ->next = p ->next;
        delete p;
    }
    return head;
}

 

 

相關文章