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

Remove Nth Node From End of List

时间:2015-04-12 17:44:42      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

Analyse: 如果链表为空,返回NULL;如果n等于链表的长度,即删除head;否则,先找到该删除位置的前一位置,将该位置的next指向被删除位置的next,并释放被删除指针的空间。第一次没有WA或TE就AC了,mark一下~~ :)

 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 *current = head;
13         int length = 0;
14         while(current){
15             length++;
16             current = current->next;
17         }
18         
19         if(length == 1) return NULL;
20         if(length == n){
21             ListNode *temp = head;
22             head = head->next;
23             delete temp;
24             return head;
25         }
26         
27         current = head;
28         for(int i = 1; i < length - n; i++) current = current->next;
29         
30         ListNode *temp = current->next;
31         current->next = current->next->next;
32         delete temp;
33         
34         return head;
35     }
36 };

 

Remove Nth Node From End of List

标签:

原文地址:http://www.cnblogs.com/amazingzoe/p/4419854.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!