建立一个线性表,依次从键盘输入的正整数(输入一个非正整数为结束),然后依次输出:
#include<iostream>
using namespace std;
struct node
{
int d;
node *next;
};
int main()
{
node *head,*p,*q;
int x;
head=0;
q=NULL;
cin>>x;
while(x>0)
{
p=new node;
p->d=x;
p->next=NULL;
if(head==NULL)
head=p;
else
q->next=p;
q=p;
cin>>x;
}
p=head;
while(p!=NULL)
{
cout<<p->d<<endl;
q=p;
p=p->next;
delete q;
}
return 0;
}
实验结果
1
2
3
1
2
0
1
2
3
1
2
Press any key to continue