C++前插法实现链表:
//前插法实现链表
#include<iostream>using namespace std;
struct node
{
int data;
node *next;
};
class linklist
{
private:
node *head;
public:
linklist();
void create();
void display();
~linklist();
};
linklist::linklist()
{
head=NULL;
}
void linklist::create()
{
node *p;
int temp=-1;
cout<<"输入链表中的数据"<<endl;
cin>>temp;
while(temp!=-1)
{
p=new node;
p->data=temp;
p->next=head;
head=p;
cin>>temp;
}
}
void linklist::display()
{
node *p=head;
while (p->next)
{
cout<<p->data<<" ";
p = p->next;
cout<<'\t';
}
cout<<p->data<<endl;
}
linklist::~linklist()
{
node *p;
while (head)
{
p = head;
head = head->next;
delete p;
p=NULL;
}
}
int main()
{
linklist list;
list.create();
list.display ();
return 0;
}