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

【Leetcode】之Remove Nth Node From End of List

2015-11-06 10:09 453 查看

一.问题描述

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.

二.我的解题思路

这道题目的要求根明确,就是仅遍历整个链表一次,然后完成对其中倒数第n个元素的删除。为了满足整个链表只能遍历一次的要求,需要设立3个指针,当遍历结束时候有:一个指向尾节点,一个指向要删除的节点,一个指向要删除的节点的前一个节点。测试通过的程序如下:

/**
* 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 * p0,* p1,* p2;
p0=p1=p2=head;
for(int i=0;i<n-1;i++){
p2=p2->next;
}
if(p2->next==NULL){
if(n==1) return NULL;
if(n>1) return head->next;
}

while(p2->next!=NULL){
p2=p2->next;
p0=p1;
p1=p1->next;
}
p0->next=p1->next;
return head;

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