#include<iostream>
using namespace std;
struct listnode
{
int data;
listnode *next;
};
class linklist
{
private:
listnode *head;
public:
linklist();
void addtolist(int data);
void display();
listnode* Head();
~linklist();
};
linklist::linklist()
{
head=new listnode;
head->next=NULL;
}
void linklist::addtolist(int data)
{
listnode *p,*q;
p=head->next;
q=new listnode;
q->data=data;
head->next=q;
q->next=p;
}
void linklist::display()
{
listnode*p=head->next;
while(p!=NULL)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
linklist::~linklist()
{
listnode *p,*q;
p=head->next;
while(p!=NULL)
{
q=head;
delete q;
p=p->next;
}
delete head;
head=NULL;
p=NULL;
q=NULL;
}
listnode* linklist::Head()
{
listnode *p;
p=head;
return p;
}
//查找链表的倒数第k个节点
listnode* findkthtotail(listnode *plisthead,unsigned int k)
{
if(plisthead->next==NULL)
return NULL;
listnode *pahead=plisthead;
listnode *pbehind=NULL;
for(unsigned int i=0;i<k-1;++i)
{
pahead=pahead->next;
if(pahead->next==NULL)
return NULL;
}
pbehind=plisthead;
while(pahead->next!=NULL)
{
pahead=pahead->next;
pbehind=pbehind->next;
}
return pbehind;
}
int main()
{
linklist list;
list.addtolist(1);
list.addtolist(2);
list.addtolist(3);
list.addtolist(4);
list.addtolist(5);
list.addtolist(6);
list.display ();
cout<<endl;
listnode* p=findkthtotail(list.Head(),7);
if(p!=NULL)
cout<<p->data<<endl;
else
cout<<"wrong"<<endl;
return 0;
}
using namespace std;
struct listnode
{
int data;
listnode *next;
};
class linklist
{
private:
listnode *head;
public:
linklist();
void addtolist(int data);
void display();
listnode* Head();
~linklist();
};
linklist::linklist()
{
head=new listnode;
head->next=NULL;
}
void linklist::addtolist(int data)
{
listnode *p,*q;
p=head->next;
q=new listnode;
q->data=data;
head->next=q;
q->next=p;
}
void linklist::display()
{
listnode*p=head->next;
while(p!=NULL)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
linklist::~linklist()
{
listnode *p,*q;
p=head->next;
while(p!=NULL)
{
q=head;
delete q;
p=p->next;
}
delete head;
head=NULL;
p=NULL;
q=NULL;
}
listnode* linklist::Head()
{
listnode *p;
p=head;
return p;
}
//查找链表的倒数第k个节点
listnode* findkthtotail(listnode *plisthead,unsigned int k)
{
if(plisthead->next==NULL)
return NULL;
listnode *pahead=plisthead;
listnode *pbehind=NULL;
for(unsigned int i=0;i<k-1;++i)
{
pahead=pahead->next;
if(pahead->next==NULL)
return NULL;
}
pbehind=plisthead;
while(pahead->next!=NULL)
{
pahead=pahead->next;
pbehind=pbehind->next;
}
return pbehind;
}
int main()
{
linklist list;
list.addtolist(1);
list.addtolist(2);
list.addtolist(3);
list.addtolist(4);
list.addtolist(5);
list.addtolist(6);
list.display ();
cout<<endl;
listnode* p=findkthtotail(list.Head(),7);
if(p!=NULL)
cout<<p->data<<endl;
else
cout<<"wrong"<<endl;
return 0;
}