题目
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.
Given n will always be valid.
Try to do this in one pass.
算法思想:
先求解单链表的长度len,由此可知,所要删除的元素位于单链表的第len-n个位置,然后找到该位置,进行删除
C++实现:
#include <iostream>
#include <stdlib.h>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *copyHead,*returnList,*p1,*p2;
copyHead=head;
returnList=NULL;
p1=NULL;
p2=NULL;
int len=0;
while(copyHead!=NULL){
len++;
copyHead=copyHead->next;
}
int i=0;
while(head!=NULL){
if(i!=(len-n)){
p2=(ListNode *)malloc(sizeof(ListNode));
p2->val=head->val;
p2->next=NULL;
if(returnList==NULL){
returnList=p1=p2;
}else{
p1->next=p2;
p1=p1->next;
p1->next=NULL;
}
}
head=head->next;
i++;
}
return returnList;
}
};
int main(){
ListNode *head,*p1,*p2,*res;
head=NULL;
p1=NULL;
p2=NULL;
int a[5]={1,2,3,4,5};
for(int i=0;i<5;i++){
p2=(ListNode *)malloc(sizeof(ListNode));
p2->val=a[i];
p2->next=NULL;
if(head==NULL){
head=p1=p2;
}else{
p1->next=p2;
p1=p1->next;
}
}
Solution sol;
res=sol.removeNthFromEnd(head,5);
while(res!=NULL){
cout<<res->val<<"->";
res=res->next;
}
}