Remove Nth Node From End of List

来源:互联网 发布:sopcast这款网络电视 编辑:程序博客网 时间:2024/06/16 22:09

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.

/** * 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 *l1=head;    ListNode *l2=head;    int step=1;ListNode *l3=head;if(l1->next==NULL&&n==1)    return NULL;    while(l2->next!=NULL||step<=n-1){    //l1=l1->next;    l2=l2->next;    if(step>n-1)    l1=l1->next;    if(step>n)    l3=l3->next;    step++;}if(l1==head){return l1->next;}if(l3->next!=NULL)l3->next=l3->next->next;elsel3->next=NULL;return head;        }};

第二版:

/** * 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;        }        ListNode * Nhead = new ListNode(0);        Nhead -> next = head;        ListNode* f = Nhead;        ListNode* s = Nhead;        int step = 1;        while(f -> next != NULL)        {                        f = f -> next;            if(step > n)            {                s = s -> next;            }            ++ step;        }        ListNode *tmp = s -> next;        tmp = tmp -> next;        s -> next = tmp;        return Nhead -> next;    }};



0 0