代码如下:
#include<iostream>
#include<stdlib.h> //malloc()函数需要用此头文件
#include<conio.h> //getche()函数需要用此头文件
using namespace std;
typedef int datatype;
typedef struct node{ //节点类型
datatype data; //数据域
struct node *next; //指针域
}linklist;
//头插法建表
linklist *CreatListF(linklist *head){
int ch;
linklist *s;
head=NULL;
while(ch=getche()!'#'){
s=(linklist*)malloc(sizeof(linklist));
s->data=ch;
s->next=head;
head=s;
}
return head;
free(s);
}
//输出函数
void Output(linklist *head) {
linklist *p=head;
cout<<endl;
cout<<"链表中的元素为:";
while(p->next!=NULL){
cout<<p->data;
p=p->next;
}
cout<<p->data;
cout<<endl;
free(p);
}
int main()
{
linklist *head;
cout<<"请输入建表数据:"<<endl;
head=CreatListF(head);
cout<<endl;
Output(head);
cout<<endl;
free(head);
}
运行后结果如下: