您的位置:首页 > Web前端 > Node.js

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

2014-12-05 05:29 441 查看
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,方便删除的操作。

代码:

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *removeNthFromEnd(ListNode *head, int n) {
ListNode *target = head;
ListNode *target_pre = NULL;
ListNode *findthelast = head;

if (head == NULL)
return head;

while(--n>0)
findthelast = findthelast->next;

while (findthelast->next) {
target_pre = target;
target = target->next;
findthelast = findthelast->next;
}

if (target_pre == NULL) {
head = target->next;
return head;
}

target_pre->next = target->next;

return head;
}
};


文艺智慧青年解法:

(需要更多理解)

class Solution
{
public:
ListNode* removeNthFromEnd(ListNode* head, int n)
{
ListNode** t1 = &head, *t2 = head;
for(int i = 1; i < n; ++i)
{
t2 = t2->next;
}
while(t2->next != NULL)
{
t1 = &((*t1)->next);
t2 = t2->next;
}
*t1 = (*t1)->next;
return head;
}
};


附录:

C++二重指针深入
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: