[LeetCode 题解]: Remove Nth Node From End of List


Given a linked list, remove thenthnode 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:
Givennwill always be valid.
Try to do this in one pass.

题解: 删除链表中的倒数第N个元素,并返回修改后的链表。

要求: 只经过一次遍历完成上述操作。

经典面试题,找到一个链表的倒数第N个元素的衍伸。 在本题中需要额外的记录第N个元素的上一个元素,用于元素删除。

寻找链表的倒数第N个元素,设置两个指针,分别从链表的头部出发,一个先遍历N个元素, 然后两个指针同时向后遍历,当前一个指针到达链表的尾部时,后一个指针则到达第N个元素。

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode *removeNthFromEnd(ListNode *head, int n) {
12         ListNode *pre,*first,*last;
13         ListNode ans(0);
14         pre=first=last=head;
15         ans.next=pre;
16         for(int i=0;i<n;i++)
17             first=first->next; //find faster pointer
18 
19         while(first!=NULL)
20         {
21             first=first->next;
22             pre = last;
23             last=last->next;
24         }
25         pre->next = last->next;
26         if(last==head) return head->next;
27         else return ans.next;        
28     }
29 };

转载请注明出处 http://www.cnblogs.com/double-win/ 谢谢!

优质内容筛选与推荐>>
1、DataGrid数据导出为xls,htm格式文件
2、线性三角化法 Triangulate
3、mysql整理
4、憋屈啊~
5、计算字符,汉字长度


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号