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.
解题思想::找到链表的长度,倒数第n个 也就是 length-n+1个, 遍历到 length-n,之后删除那一个节点。
#include <iostream>
using namespace std;
typedef struct ListNode
{ int val;
struct ListNode *next;
}Node;
struct ListNode* removeNthFromEnd(struct ListNode* head, int n)
{
struct ListNode* pCurrent=head; //保护head
int length =0;
int flag;
while(pCurrent!=NULL)
{
length++;
pCurrent=pCurrent->next;
}
//从头再来;
pCurrent=head;
flag=length-n;
if(length ==1)
return NULL;
if (0==flag)
{
head=pCurrent->next;
// head->next=pCurrent->next->next;
}
flag--;
for (;flag>0;flag--)
{
pCurrent=pCurrent->next;
}
if(n==1)
pCurrent->next=NULL;
else
pCurrent->next=pCurrent->next->next;
return head;
}
int main()
{
Node *head=(Node*)malloc(sizeof(Node));
Node *p,*q,*q1;
int key;
p=(Node*)malloc(sizeof(Node));
q1=q=head;
int i;
for (i=1;i<4;i++)
{
p->val=i;
head->next=p;
head=p;
p=(Node*)malloc(sizeof(Node));
}
head->next=NULL;
cout<<"原链表数据: "<<endl;
q1=q1->next;
while (q1!=NULL)
{
cout<<q1->val<<" ";
q1=q1->next;
}
cout<<endl;
cout<<"输入要删除的第几个:";
cin>>key;
p=removeNthFromEnd(q->next,key);
cout<<"删除一个"<<key<<"之后的链表数据: "<<endl;
while (p!=NULL)
{
cout<<p->val<<" ";
p=p->next;
}
cout<<endl;
free(p);
free(head);
return 0;
}