首页 > 其他 > 详细

Remove Nth Node From End of List

时间:2015-10-17 16:00:35      阅读:184      评论:0      收藏:0      [点我收藏+]
 1 class Solution {
 2 public:
 3     ListNode* removeNthFromEnd(ListNode* head, int n) {
 4         if(n<=0||head==NULL) return head;
 5        ListNode prehead(0);
 6       prehead.next=head;
 7        ListNode *p=head;
 8        int length=0,i;
 9        while(p->next)
10        {
11            length++;
12            p=p->next;
13        }
14        p=&prehead;
15        length++;
16        if(n>length)n=n%length;
17        i=length-n;
18      
19        while(i--)p=p->next;
20       if(n==1) p->next=NULL;
21       else  p->next=p->next->next;
22       return prehead.next;
23     }
24 };

效率不高,还是以前的思路,没有创新,下面是别人的一个比较好的

 1 class Solution {
 2 public:
 3     ListNode* removeNthFromEnd(ListNode* head, int n) {
 4         if(n<=0||head==NULL) return head;
 5        ListNode prehead(0);
 6       prehead.next=head;
 7        ListNode *p=&prehead;
 8        head=&prehead;
 9        while(n--)
10        {
11            p=p->next;
12        }
13        while(p->next)
14        {
15            p=p->next;
16            head=head->next;
17        }
18        head->next=head->next->next;
19        
20       return prehead.next;
21     }
22 };

凡是说倒着第几个都可以利用顺着的第几个打个标记,然后另一个从头开始,这个继续直到这个到结尾。

Remove Nth Node From End of List

原文:http://www.cnblogs.com/daocaorenblog/p/4887518.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!