[LeetCode] 085: Remove Nth Node From End of List
来源:互联网 发布:怎么上淘宝的每日好店 编辑:程序博客网 时间:2024/06/06 12:23
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.
[Solution]
说明:版权所有,转载请注明出处。Coder007的博客/**
* 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) {
// Note: The Solution object is instantiated only once and is reused by each test case.
// invalid
if(n <= 0 || NULL == head)return head;
// move the first pointer n steps forward
int i = 0;
ListNode *p = head;
for(i = 0; i < n && p != NULL; ++i){
p = p->next;
}
// n is larger than the length of the list
if(i != n)return head;
// the node to be deleted is the head of the list
if(NULL == p){
ListNode *q = head;
head = head->next;
delete q;
return head;
}
// get the node to be deleted
ListNode *pre = head;
ListNode *q = head;
while(p != NULL){
pre = q;
q = q->next;
p = p->next;
}
// delete the node
pre->next = q->next;
delete q;
return head;
}
};
- [LeetCode] 085: Remove Nth Node From End of List
- LeetCode[Linked List]: Remove Nth Node From End of List
- 19. Remove Nth Node From End of List leetcode list
- [Leetcode]LeetCode 19: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
- leetcode 40: 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] 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 19: Remove Nth Node From End of List
- LeetCode - Remove Nth Node From End of List
- LeetCode | Remove Nth Node From End of List
- [LeetCode] 080: Remove Duplicates from Sorted Array
- [LeetCode] 081: Remove Duplicates from Sorted Array II
- [LeetCode] 082: Remove Duplicates from Sorted List
- [LeetCode] 083: Remove Duplicates from Sorted List II
- [LeetCode] 084: Remove Element
- [LeetCode] 085: Remove Nth Node From End of List
- 幂指函数求导公式——备忘
- [LeetCode] 086: Restore IP Addresses
- Oracle 11g Data Guard搭建物理Standby数据库(一)
- [LeetCode] 087: Reverse Integer
- [LeetCode] 088: Reverse Linked List II
- 排序算法学习笔记
- [LeetCode] 089: Reverse Noes in k-Group
- [LeetCode] 090: Roman to Integer