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,
题意:
给出一个链表,删除倒数第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;
}
};
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;
}
};
相关文章推荐
- LeetCoder 19. Remove Nth Node From End of List
- 【leetcode】11 Remove Nth Node From End of List
- [Leetcode] Remove Nth Node From End of List
- [LeetCode] Remove Nth Node From End of List
- [面试真题] LeetCode:Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List
- Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List
- Remove Nth Node From End of List
- Remove Nth Node from End of List
- the code of Remove Nth Node From End of List
- Remove Nth Node From End of List
- LeetCode 笔记系列四 Remove Nth Node From End of List
- Leetcode 19 Remove Nth Node From End of List
- [Leetcode 19] 19 Remove Nth Node From End Of List
- Remove Nth Node From End of List
- leetcode 40: Remove Nth Node From End of List
- [Leetcode] Remove Nth Node From End of List
- leetcode Remove Nth Node From End of List
- LeetCode_Remove Nth Node From End of List