#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
struct Node{
ElemType data;
struct Node *next;
};
typedef struct Node SLink;
SLink *creatNode(){
SLink *node=(SLink*)malloc(sizeof(SLink));
//创建头结点
node->next=NULL;
//指针置空
return node;
}
//创建链表
SLink *init1(){
return creatNode();
}
//打印链表
void print(SLink *list){
SLink *p=list->next;
int m=1;
printf("链表打印结果如下:
");
if(list->next==NULL){
printf("链表为空");
return;
}
while(list->next!=NULL){
printf("第%d个数为%d
",m++,p->data);
p=p->next;
}
}
//输入链表
void creatdata(SLink *list){
SLink *p=list;
int n,m=1;
printf("请输入第%d个数(输入-1以停止输入)
",m);
while(scanf("%d",&n),n!=-1){
SLink *node=creatNode();
node->data=n;
p->next=node;
p=p->next;
m++;
}
p->next=NULL;
}
//在头位置插入
void intofront(SLink *list){
SLink *p=list->next;
int n;
printf("输入你想插入的数字:");
SLink *node=creatNode();
scanf("%d",&n);
node->data=n;
list->next=node;
node->next=p;
}
int main(){
SLink *list=init1();//创建链表
while(true){
printf("1.创建链表
2.在头位置插入
3.打印
");
int n;
printf("请输入操作序号:
");
scanf("%d",&n);
switch(n)
{
case 1: creatdata(list); break;//输入链表
case 2: intofront(list); break;//在头位置插入
case 3: print(list); break;//打印
}
}
}