题目如下:
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;
}
};