Leetcode 19. Remove Nth Node From End of List

来源:互联网 发布:虐杀原形帧数优化补丁 编辑:程序博客网 时间:2024/05/22 11:57

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.

题目大意:删除链表中倒数第n个节点。

题目分析:使用双指针相聚n-1,当第二个指针遍历到链表尾部则第一个指针就是要删除的节点指针。这里有个问题,因为要删除节点,所以不添加头结点的话,要把删除第一个节点,和其他节点区分开来(第一个节点没有前驱)。如果添加则可以统一处理。下面分别是两种代码,运行时间都是4ms

方法一(不添加头节点):

/** * 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||head->next==NULL) return NULL;        ListNode* first=head;        ListNode* second=head;        for(int i=0;i<n-1;i++)            second=second->next;        if(second->next==NULL){//删除第一个节点            head=head->next;            return head;        }        while(second->next->next){            second=second->next;            first=first->next;        }        first->next=first->next->next;        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 h(INT_MAX);        h.next=head;                ListNode *pfirst=&h;        ListNode *psecond=&h;        ListNode *temp;//释放被删除的空间                for(int i=0;i<n;i++)            psecond=psecond->next;        while(psecond->next){            psecond=psecond->next;            pfirst=pfirst->next;        }        temp=pfirst->next;        pfirst->next=pfirst->next->next;        delete temp;        return h.next;    }};


0 0
原创粉丝点击