Chinaunix首页 | 论坛 | 博客
  • 博客访问: 166124
  • 博文数量: 13
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 350
  • 用 户 组: 普通用户
  • 注册时间: 2014-04-03 15:44
文章分类

全部博文(13)

文章存档

2015年(3)

2014年(10)

我的朋友

分类: C/C++

2015-07-17 02:00:44

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.



  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. #include <iostream>
  10. using namespace std;

  11. class Solution {
  12. public:
  13.     ListNode* removeNthFromEnd(ListNode* head, int n) {
  14.     ListNode* end_p,* p,*pre_p;
  15.     
  16.     end_p=p=pre_p=head;
  17.     
  18.     
  19.     if(p==NULL) return head;
  20.     else if(p->next == NULL )
  21.     {
  22.         delete(p);
  23.         head=NULL;
  24.         return head;
  25.     }
  26.     
  27.     n--;
  28.     while(n)
  29.     {
  30.         end_p = end_p->next;
  31.         n--;
  32.     }
  33.     
  34.     
  35.     while(end_p->next!=NULL)
  36.     {
  37.         pre_p=p;
  38.         end_p=end_p->next;
  39.         p=p->next;
  40.     }
  41.     
  42.  
  43.     if(pre_p==p) head = p->next;
  44.     else pre_p->next=p->next;
  45.     delete(p);

  46.     
  47.     return head;
  48.     }
  49. };

阅读(894) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~