Remove Nth Node From End of List

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 <stdio.h>
#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值