#include <stdio.h> |
#include <stdlib.h> |
typedef struct Node{ |
int data; //数 |
struct Node *next; //指针 |
}*Linklist,Node; //node是指向结构体的一个结构体变量linklist指向链表的指针 |
Linklist creat( int n) //建立 |
{ |
Linklist head,r,p; |
int x,i; |
head=(Node*) malloc ( sizeof (Node)); //开辟空间 |
r=head; //r指向头 |
printf ( "输入数字:\n" ); |
for (i=n;i>0;i--) |
{ |
scanf ( "%d" ,&x); |
p=(Node*) malloc ( sizeof (Node)); |
p->data=x; |
r->next=p; |
r=p; |
} |
r->next=NULL; |
return head; |
} |
void output(Linklist head) //输出 |
{ |
Linklist p; |
p=head->next; |
do { |
printf ( "%3d" ,p->data); |
p=p->next; |
} while (p); |
printf ( "\n" ); |
} |
void find(Linklist head, int x) //寻找 |
{ |
int i=0,j=0; |
Linklist p; |
p=head; |
while (p){ |
if (p->data==x){ |
printf ( "元素存在,他在线性表的第%d个位置上\n" ,i++); |
p=p->next; |
j=1;} |
else { |
p=p->next; |
i++;} |
} |
if (j==0) |
printf ( "查找的元素不存在\n" ); |
} |
void insert(Linklist head, int i, int x) //插入 |
{ |
int j=0; |
Linklist p,s; |
p=head; |
while (p&&j<i-1) |
{ |
p=p->next; |
j++; |
} |
if (!p||j>i-1) |
printf ( "\n指定的插入位置不存在" ); |
s=(Linklist) malloc ( sizeof (Node)); |
s->data=x; |
s->next=p->next; |
p->next=s; |
} |
void delete_ith(Linklist head, int i) //删除按位置 |
{ |
int j=0; |
Linklist p; |
p=head; |
while (p&&j<i-1) |
{ |
p=p->next; |
j++; |
} |
if (!p||j>i-1) |
printf ( "\n删除的位置不合理" ); |
p->next=p->next->next; |
} |
void delete1(Linklist head, int i) //删除按照元素 |
{ |
Linklist p; |
p=head; |
while (p->next) |
{ |
if (p->next->data==i){ |
p->next=p->next->next; |
} |
else { |
p=p->next; |
|
} |
} |
} |
void length(Linklist head) //长度 |
{ int j=0; |
Linklist p; |
p=head->next; |
while (p) |
{ |
p=p->next; |
j++; |
|
} |
printf ( "\n%d" ,j); |
} |
void null(Linklist head) //判断是否为空 |
{ int j=0; |
Linklist p; |
p=head->next; |
while (p) |
{ |
p=p->next; |
j++; |
|
} |
if (j==0) |
printf ( "\n空" ); |
else |
printf ( "\n不为空" ); |
} |
/*void free(Linklist head) |
{ |
Linklist p; |
p=head; |
while(p) |
{ |
p=p->next; |
delete head; |
head=p; |
} |
}*/ |
void printi(Linklist head, int i) // |
{ |
int j=0; |
Linklist p; |
p=head; |
while (p&&j<i) //找到第i个元素 |
{ |
p=p->next; |
j++; |
} |
printf ( "%d" ,p->data); |
} |
void main() |
{ |
Linklist head; |
int n,x,position,i,j,a; |
printf ( "输入数字的个数n\n" ); |
scanf ( "%d" ,&n); |
head=creat(n); |
printf ( "输出数字\n" ); |
output(head); |
printf ( "输入你要查的数x:\n" ); |
scanf ( "%d" ,&x); |
find(head,x); |
printf ( "输入你要插入的数x和他的pos位置\n" ); |
scanf ( "%d%d" ,&x,&position); |
insert(head,position,x); |
output(head); |
printf ( "输入你要删除的第i个元素\n" ); |
scanf ( "%d" ,&i); |
delete_ith(head,i); |
printf ( "删除后的链表为\n" ); |
output(head); |
printf ( "长度为" );length(head); printf ( "\n" ); |
null(head); |
//free(head); |
output(head); |
scanf ( "%d" ,&j); |
printi(head,j); printf ( "\n" ); |
output(head); |
scanf ( "%d" ,&a); |
delete1(head,a); |
output(head); |
} |