最后一个do while循环不起作用,无法起到反复选项。
#include <stdio.h>
#include<stdlib.h>
#include <malloc.h>
typedef int Datatype;
typedef struct linknode
{
Datatype data;
struct linknode *next;
}Linklist;
Linklist *Initlist()
{
Linklist *head;
head = (Linklist*)malloc(sizeof(Linklist));
head->next = NULL;
return head;
}
void creatLinklist(Linklist *head,int n)
{
Linklist *s,*last;
int i;
last = head;
printf("请输入%d个整数:",n);
for(i = 0;i<n;i++)
{
s = (Linklist*)malloc(sizeof(Linklist));
scanf("%d",&s->data);
s->next = NULL;
last->next = s;
last = s;
}
printf("建立单链表成功!");
}
int lenlist(Linklist *head)
{
Linklist *p = head->next;
int j = 0;
if(p != head)
{
p = p->next;
j++;
return j;
}
}
void locate(Linklist *head,Datatype x)
{
int j = 1;
Linklist *p;
p = head->next;
while(p != head && p->data != x)
{
p = p->next;
j++;
}
if(p != head)
{printf("在表的第%d位找到为%d的结点!",j,x);}
else
{printf("未找到结点!");}
}
void enlist(Linklist *head,int i,Datatype x)
{
int j = 0;
Linklist *s,*p;
p = head;
while(p->next != head && j<i-1)
{
p = p->next;
j++;
}
if(p != head)
{
s = (Linklist*)malloc(sizeof(Linklist));
s->data = x;
s->next = p->next;
p->next = s;
printf("插入成功!");
}
else{printf("插入失败!");}
}
void delist(Linklist *head,int i,Datatype x)
{
int j = 0;
Linklist *s,*p;
p = head;
while(p->next != head && j<i-1)
{
p = p->next;
j++;
}
if(p != head)
{
s = p->next;
x = s->data;
p->next = s->next;
free(s);
printf("删除%d位置上的%d成功!",i,x);
}
else{printf("删除失败");}
}
void dislist(Linklist *head)
{
Linklist *p;
p = head->next;
while(p != head)
{
printf("%5d",p->data);
p = p->next;
}
}
int menu()
{
int n;
printf("\n\t===========================================\n");
printf("\t\t 单循环链表基础操作");
printf("\n\t===========================================\n");
printf("\n\t1.建立");
printf("\n\t2.插入");
printf("\n\t3.删除");
printf("\n\t4.求表长");
printf("\n\t5.遍历");
printf("\n\t0.退出\n");
do
{
printf("\n\t\t 请输入0-5:");
scanf("%d",&n);
}while((n<0)||(n>5));
return n;
}
int main()
{
Linklist *head;
Datatype x;int n,i;
int kk;
do
{
kk = menu();
switch(kk)
{
case 1:
head = Initlist();
printf("请输入要建立的线性表的长度:");
scanf("%d",&n);
creatLinklist(head,n);
printf("建立完成!线性表为:");
dislist(head);
break;
case 2:
printf("请输入要插入的位置:");
scanf("%d",&i);
printf("请输入要插入的值:");
scanf("%d",&x);
enlist(head,i,x);
printf("插入后的线性表为:");
dislist(head);
break;
case 3:
printf("请输入要删除的位置:");
scanf("%d",&i);
delist(head,i,x);
printf("删除后的线性表为:");
dislist(head);
break;
case 4:
printf("表长为:%d!",lenlist(head));
break;
case 5:
printf("遍历线性表的数据:");
dislist(head);
break;
case 0:
exit(0);
}
}while(kk != 0);
return 0;
}