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

LeetCoder_____Remove Nth Node From End of List(11)

2017-03-22 19:52 344 查看
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.


题意:

给出一个链表,删除倒数第n个节点。

分析:

两个指针p1,p2,一个指针p1先走n步,然后同时一起走,当p1为NULL,删除p2所处节点即可。

在面试中出现这种题目需要注意一些地方:(程序的鲁棒性)

1.给出的head指针为NULL。

2.给出的n为非正数。

3.给出的n超过链表的长度。

4.当删除的节点为头节点或者尾节点。

代码:

class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if(head == NULL || n == 1 && head->next == NULL) return NULL;
if(n <= 0)return head;
ListNode* p1,*p2;
p1 = p2 = head;
if(n == 1){
while(p1->next->next != NULL)
p1 = p1->next;
p1->next = NULL;
return head;
}
for(int i = 0 ; i < n ; i ++){
if(p1 == NULL) return head->next;
p1 = p1->next;
}
while(p1 != NULL){
p1 = p1->next;
p2 = p2->next;
}
p2->val = p2->next->val;
p2->next = p2->next->next;
return head;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: