LeetCode-Remove Nth Node From End of List-移除从链表结尾数第n个结点-双指针链表操作

https://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/

一道很典型的题。使用两个距离为n的指针,往后移动到后面遇到尾端。第一个指针指向结点就是待删除结点。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *removeNthFromEnd(ListNode *head, int n) {
        if (head==NULL) return NULL;
        if (n==0) return NULL;
        ListNode *q=head;
        int count=1;
        while(q->next && count<n){
            q=q->next;
            count++;
        }
        if (count<n) return head;
        ListNode *lp=NULL,*p=head;
        while(q->next){
            q=q->next;
            lp=p;
            p=p->next;
        }
        if (lp==NULL) {
            head=p->next;
            delete p;
        }
        else{
            lp->next=p->next;
            delete p;
        }
        return head;
    }
};

 

posted @ 2014-10-14 15:40  zombies  阅读(151)  评论(0编辑  收藏  举报