leetcode之路019 Remove Nth Node From End of List

来源:互联网 发布:万达网络科技集团待遇 编辑:程序博客网 时间:2024/05/29 15:01


题目大意:从一个链表中删除第n个元素。如:

  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.
注意:n总是有效的,而且要在一趟内完成。


思路:相差n个,只能访问一趟,可以考虑用两个指针操作,即当第一个指针走了n步时,第二个指针从head开始和第一个指针一起前进。当第一个指针指向最尾端时,第二个指针即是需要删除的位置。

比较简单,需要注意的是边界情况。ac的代码如下,运行时间4ms:

class Solution {public:    ListNode* removeNthFromEnd(ListNode* head, int n) {ListNode* in;ListNode* ne=head;while((n--)&&ne)ne=ne->next;in=head;ListNode* temp=in;while(ne!=NULL){temp=in;in=in->next;ne=ne->next;}if(in==head)head=head->next;elsetemp->next=in->next;return head;    }};




0 0
原创粉丝点击