LeetCode(19) Remove Nth Node From End of List
阿新 • • 發佈:2019-02-10
題目如下:
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.
題目比較簡單。注意分為刪除頭結點和非頭結點這兩種情況即可。提交的標頭檔案如下:
/** * 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) { if(head==NULL) return NULL; int list_length=0; int index1=0; ListNode* p=head; ListNode* q=NULL; while(p!=NULL){ list_length++; p=p->next; } if(list_length<n) { //題目說了給定的n是valid的。貌似不需要此步的測試了。 return NULL; }else if(list_length==n){ p=head; head=head->next; delete p; return head; }else { index1=list_length-n+1; p=head; for(int i=0;i<index1-2;i++) p=p->next; q=p->next; p->next=p->next->next; delete q; return head; } } };
我是用的main函式如下:
// main.cpp #include <iostream> #include "Solution.h" int main(int argc, const char * argv[]) { int array[5]={-1,-2,-3,-4,-5}; ListNode* head=NULL; ListNode* tail=NULL; for(int i=0;i<5;i++) { ListNode* p=new ListNode(array[i]); if(head==NULL){ head=p; tail=p; }else{ tail->next=p; tail=p; } } ListNode* p=head; while(p!=NULL){ std::cout<<p->val<<"\t"; p=p->next; } Solution s1; head=s1.removeNthFromEnd(head, 100); std::cout<<std::endl; std::cout << "019 Hello, World!\n"; while(head!=NULL){ std::cout<<head->val<<"\t"; head=head->next; } std::cout<<std::endl; return 0; }
update: 2014-12-10
/**
* 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) {
int length = 0;
ListNode* current = head;
while (current != NULL) {
length++;
current = current -> next;
}
n = length - n -1; // previous node of the node to be deleted
current = head;
if (n < 0) // NOTE: corner case, delete head
return head->next;
while (n > 0) {
current = current->next;
n--;
}
current->next = current->next->next;
return head;
}
};
update: 2015-01-22
更巧妙的思路:
一個指標先走n步,然後兩個同步走,直到第一個走到終點,第二個指標就是需要刪除的節點。注意討論head指標的情況。
class Solution {
public:
ListNode *removeNthFromEnd(ListNode *head, int n) {
if (n == 0) return head;
ListNode* first = head;
ListNode* second = head;
int step = 0;
while (step < n ) {
first = first->next;
step++;
}
if (first == NULL)
return head->next;
while (first!= NULL && first->next != NULL) {
first = first->next;
second = second->next;
}
if(second->next != NULL)
second->next = second->next->next;
return head;
}
};