19. Remove Nth Node From End of List

来源:互联网 发布:linux怎么复制命令 编辑:程序博客网 时间:2024/06/08 03:36

题目

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,前n步内只移动p指针,然后移动k-n次t指针,则循环结束后t指向倒数第n+1个元素,其中h指针保证t在第n+1次循环时保持指向head不动,并且如果h不发生变化证明需要删去的是头结点,返回head->next。

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


0 0
原创粉丝点击