【Leetcode】【Easy】Remove Nth Node From End of List

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.

 

普通青年解法:

设置三个指针A\B\C,指针A和B间隔n-1个结点,B在前A在后,用指针A去遍历链表直到指向最后一个元素,则此时指针B指向的结点为要删除的结点,指针C指向指针B的pre,方便删除的操作。

代码:

 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 *target = head;
13         ListNode *target_pre = NULL;
14         ListNode *findthelast = head;
15         
16         if (head == NULL)
17             return head;
18         
19         while(--n>0)
20             findthelast = findthelast->next;
21         
22         while (findthelast->next) {
23             target_pre = target;
24             target = target->next;
25             findthelast = findthelast->next;
26         }
27         
28         if (target_pre == NULL) {
29             head = target->next;
30             return head;
31         }
32         
33         target_pre->next = target->next;
34         
35         return head;
36     }
37 };

 

文艺智慧青年解法:

 (需要更多理解)

 1 class Solution
 2 {
 3 public:
 4     ListNode* removeNthFromEnd(ListNode* head, int n)
 5     {
 6         ListNode** t1 = &head, *t2 = head;
 7         for(int i = 1; i < n; ++i)
 8         {
 9             t2 = t2->next;
10         }
11         while(t2->next != NULL)
12         {
13             t1 = &((*t1)->next);
14             t2 = t2->next;
15         }
16         *t1 = (*t1)->next;
17         return head;
18     }
19 };

 

附录:

C++二重指针深入

posted @ 2014-12-05 05:29  胡潇  阅读(174)  评论(0编辑  收藏  举报