码迷,mamicode.com
首页 > 其他好文 > 详细

Remove Nth Node From End of List

时间:2015-10-17 16:01:42      阅读:151      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!