单链表.c
来自「用c写的数据结构链表的操作」· C语言 代码 · 共 162 行
C
162 行
#include<stdio.h>
#include<stdlib.h>
typedef int elemtype;
typedef struct node
{
elemtype data;
struct node *next;
}node,*linklist;
linklist creatlink(linklist L,int length)
{
int i=1;
node *head,*p,*q;
head=L;
printf("Enter the length of the list:");
scanf("%d",&length);
p=(node*)malloc(sizeof(node));
head->next=p;
printf("--------------------------------\n");
printf("enter %d datas\n",length);
printf("no.1:");
scanf("%d",&p->data);
for(i=2;i<=length;i++)
{
q=(node*)malloc(sizeof(node));
printf("enter no.%2d data:",i);
scanf("%d",&q->data);
p->next=q;
p=q;
}
p->next=NULL;
return(L);
}
elemtype getlink(linklist L,int i)
{
elemtype e;
node *p;
int j;
printf("----------------------\n");
printf("the no. you want to find:");
scanf("%d",&i);
p=L->next;
j=1;
while(p&&j<i)
{
p=p->next;
j++;
}
if(j!=i)
printf("error!\n");
e=p->data;
return(e);
}
inslink(linklist L,int i)
{
node *p,*q;
int j;
p=L;
j=0;
printf("the locotion you want to insert:");
scanf("%d",&i);
while(p&&j<i-1)
{
p=p->next;
j++;
}
if(j!=i-1)
{
return(0);
}
if((q=(node*)malloc(sizeof(node)))==NULL)
exit(1);
q->data=i;
q->next=p->next;
p->next=q;
printf("data to insert:");
scanf("%d",&q->data);
}
dellink(linklist L,int i)
{
elemtype e;
node *p,*q;
int j;
printf("the location you want to delete:");
scanf("%d",&i);
p=L;
j=0;
while(p&&j<i-1)
{
p=p->next;
j++;
}
if(!p||j>i-1)
printf("error!\n");
q=p->next;
p->next=p->next->next;
e=q->data;
free(q);
return(e);
}
prilink(linklist L)
{
int i=0;
node *p;
printf("the data of list is\n");
p=L;
while(p->next)
{
p=p->next;
printf("%d\n",p->data);
i++;
}
printf("the length of the list is:%d\n",i);
}
void menu(void)
{
int i,length,k;
char ch;
linklist L;
clrscr();
printf("\n\n\n\t\t+------------------------------------+");
printf("\n\t\t| 1.creat linklist |");
printf("\n\t\t| 2.get linklist |");
printf("\n\t\t| 3.insert linklist |");
printf("\n\t\t| 4.delete linklist |");
printf("\n\t\t| 5.print linlist |");
printf("\n\t\t| 0.exit |");
printf("\n\t\t+------------------------------------+\n");
printf("make your choice:");
scanf("%d",&k);
do
{
switch(k)
{
case 0:exit(0);
case 1:creatlink(L,length);break;
case 2:printf("%d\n",getlink(L,i));break;
case 3:inslink(L,i);break;
case 4:printf("the data was deleted is%d\n",dellink(L,i));break;
case 5:prilink(L);break;
default:printf("overflow!\n");
}
printf("return?(y/n)");
ch=getchar();
if(getchar()=='n'||getchar()=='N')
{
printf("make your choice:");
scanf("%d",&k);
}
else
{
menu();
}
}while(9);
}
main()
{
clrscr();
menu();
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?