标签:
#include<stdio.h>
#include<malloc.h>
#include<conio.h>
#include<stdlib.h>
#include "math.h"
#define NULL 0
#define LEN sizeof(struct cle)
struct cle
{
int num;
struct cle *next;
};
int n;
char c=0;
/*定义输入函数*/
struct cle *input(void)
{
char c;
struct cle *head;
struct cle *p1,*p2;
n=0;
p1=(struct cle *)malloc(LEN);/*开辟一个新单元*/
p2=(struct cle *)malloc(LEN);
printf("请输入第一个元素: ");
scanf("%d",&p1->num);
do{
n=n+1;
if(n==1) head=p1;
else
p2->next=p1;
p2=p1;
p1=( struct cle*)malloc(LEN);
printf("请输入下一个元素: ");
scanf("%d",&p1->num);
c=getch();
}
while((c==‘o‘)&&(p1->num!=0));
p2->next=NULL;
return(head);
}
/*定义一个输出链表的函数*/
void display( struct cle *head)
{
struct cle *p;
p=head;
printf("所以元素:");
if(head!=NULL)
do
{
printf("%3d",p->num);
p=p->next;
} while(p!=NULL);
}
/*定义删除函数*/
struct cle *del( struct cle *head)
{
int num;
char c;
struct cle *p1,*p2;
do
{
if(head==NULL)
{
printf("\n线性表为空表!\n");
return(head);
}
printf("请输入要删除的元素: ");
scanf("%d",&num);
p1=head;
while(num!=p1->num &&p1->next!=NULL)
{
p2=p1;
p1=p1->next;
}
if(num==p1->num)
{
if(p1==head)
head=p1->next;
else
p2->next=p1->next;
printf("已删除元素%d",num);
n=n-1;
}
else
printf("该元素不存在!");
printf("是否继续删除,Y/N");
c=getch();
}while(c==‘Y‘);
return (head);
}
/*定义插入函数*/
struct cle *insert(struct cle *head)
{
int num;
struct cle *p0,*p1,*p2;
int i,k,j=0;
char c;
do
{
p0=(struct cle *)malloc(LEN);
printf("请输入要插入的元素: ");
scanf("%d",&p0->num);
if(head==NULL)
{
head=p0;
p0->next=NULL;
}
else
{
p1=head;
n=0;
for(k=1;p1->next!=NULL;k++)
{
n=n+1;
p1=p1->next;
}
p2=head;
printf("请输入元素插入的位置:");
scanf("%d",&i);
while(i<=n+1&&j<i-1)
{
p2=p2->next;
++j;
}
if(i>n+1||j>i-1) return 0;
p0->next=p2->next;
p2->next=p0;
}
printf("是否继续插入,Y/N");
c=getch();
}while(c==‘Y‘);
return(head);
}
/*定义main函数*/
main()
{
struct cle *head;
int del_num,insert_num;
int i;
printf("```主菜单```\n");
printf("1.输入函数\n");
printf("2.显示函数\n");
printf("3.删除函数\n");
printf("4.插入函数");
char ch=‘y‘;
while(ch==‘y‘)
{
printf("\n请输入你的选择:");
scanf("%d",&i);
switch(i)
{
case 1: head=input(); break;
case 2: display(head); break;
case 3: del(head); break;
case 4: insert(head); break;
}
}
system("pause");
return 0;
}
标签:
原文地址:http://www.cnblogs.com/locean/p/5264645.html