现在的位置: 首页 > 综合 > 正文

leetcode Remove Nth Node From End of List

2019年08月14日 ⁄ 综合 ⁄ 共 440字 ⁄ 字号 评论关闭

题目说:Try to do this in one pass

只用一遍遍历的话,p1先走n节点,p2再走,等到p1到达链表尾的时候p2正好在倒数第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) {
       ListNode *h;
       h->next=head;//处理删除第一个节点时的情况
       ListNode *p1=h;
       ListNode *p2=h;
       
       for(int i=0;i<n;i++)
                p1=p1->next;
        while(p1->next!=NULL)
        {
            p1=p1->next;
            p2=p2->next;
        }
        
        p2->next=p2->next->next;
        
        return h->next;
    }
};

抱歉!评论已关闭.