Remove Nth Node From End of List

来源:互联网 发布:微拍堂用软件加粉丝 编辑:程序博客网 时间:2024/04/30 10:04

今晚做的最顺的题有木有!一次过有木有!

解决方案是,维护一个长度为n + 1的队列,如果超了的话,就把最前面的元素移出去。这样到链表遍历玩的时候,刚好队列头在需要删除的元素前面的位置。

/** * 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) {        int i = 1;        ListNode *p = head, *fake = new ListNode(0);        ListNode *q = fake;        q->next = head;        while (p != NULL) {            if (i >= n + 1)                q = q->next;            else                i++;            p = p->next;        }        q->next = q->next->next;        return fake->next;    }};

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

0 0