我刚学C不久,看到链表这就写了这个.给刚学C的朋友们,希望大家共同进步,也希望高手们也看看提出缺点和不足.
谢谢!
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
////////链表结构体////////
struct chain
{
char data;
struct chain *next;
};
////////声明////////
int Menu();
struct chain *Create(void);
struct chain *Insert(struct chain *head);
struct chain *Del(struct chain *head);
void Free(struct chain *head);
void print(struct chain *head);
////////主函数////////
void main()
{
struct chain *top;
for (; ;)
{
switch (Menu())
{
case 1:
top=Create();
print(top);
printf("\n");
break;
case 2:
top=Insert(top);
print(top);
printf("\n");
break;
case 3:
top=Del(top);
print(top);
printf("\n");
break;
case 4:
Free(top);
exit(0);
}
}
}
////////菜单函数////////
int Menu()
{
char s;
int num;
printf("1.建立链表\n");
printf("2.插入元素\n");
printf("3.删除元素\n");
printf("4.退出\n");
do
{
s=getchar();
num=(int)s-48;
}while (num<0 || num>4);
return num;
}
////////建立链表////////
struct chain *Create(void)
{
struct chain *head,*tail,*p;
head=tail=NULL;
char ch;
printf("输入链表元素:");
getchar();
while ((ch=getchar())!='\n')
{
p=(struct chain *)malloc (sizeof(struct chain));
p->data=ch;
p->next=NULL;
if (head==NULL)
{
head=tail=p;
}
else
{
tail=tail->next=p;
}
}
return head;
}
////////插入函数////////
struct chain *Insert(struct chain *head)
{
struct chain *p,*q,*insert;
char c,d;
printf("输入插入元素位于之前数据:");
getchar();
c=getchar();
printf("输入插入元素:");
getchar();
d=getchar();
insert=(struct chain *)malloc (sizeof(struct chain));
insert->data=d;
if (head==NULL)
{
head=insert;
insert->next=NULL;
}
if (head->data==c)
{
insert->next=head;
head=insert;
}
else
{
p=head;
while ((p->data!=c) && (p->next!=NULL))
{
q=p;
p=p->next;
}
if (p->data==c)
{
q->next=insert;
insert->next=p;
}
else
{
p->next=insert;
insert->next=NULL;
}
}
return (head);
}
////////删除函数////////
struct chain *Del(struct chain *head)
{
struct chain *p=NULL,*q=NULL;
char del;
printf("输入要删除的数据:");
getchar();
del=getchar();
if (head==NULL)
{
printf("空链表\n");
}
else if (head->data==del)
{
p=head;
head=head->next;
}
else
{
p=head;
while ((p->data!=del) && (p->next!=NULL))
{
q=p;
p=p->next;
}
if (p->data !=del)
{
printf("没有要删除的数据");
}
else
{
q->next=p->next;
free(p);
}
}
return (head);
}
////////输出函数////////
void print(struct chain *head)
{
while (head!=NULL)
{
printf("%c",head->data);
head=head->next;
}
}
////////释放内存////////
void Free(struct chain *head)
{
struct chain *p,*q;
p=head;
while (p!=NULL)
{
q=p->next;
free(p);
p=q;
}
}
[分享]简单的链表操作