[LeetCode] 085: Remove Nth Node From End of List

来源:互联网 发布:怎么上淘宝的每日好店 编辑:程序博客网 时间:2024/06/06 12:23
[Problem]

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]

/**
* 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;
}
};

说明:版权所有,转载请注明出处。Coder007的博客