c语言+单amp;,c语言实现单链表
#include
#include
typedef struct node //建立一个结构体
{
int data;
struct node *next;
} node ;
node *createlist(int n)
{
node *l;
node *p;
node *q;
int i;
l = (node * )malloc(sizeof(node)); //分配一个node类型的存储空间
l -> next = NULL;
q = l;
for(i = 1; i <= n; i++)
{
p = (node * )malloc(sizeof(node));
printf("Please enter the value of number %d\n",i);
scanf("%d",&p -> data);
getchar();
p -> next = NULL;
q -> next = p;
q = p ;
}
return l;
} //函数createlist()
void PrintList(node *l)
{
node *t;
t = l -> next;
printf("the value is") ;
while(t)
{
printf("%3d",t -> data);
t = t -> next ;
}
putchar('\n');
} //函数PrintList()
int locate(node *l) //查找
{
int e; //要查找的值
node *p;
int i = 1;
printf("Please enter the number which you want to locate:\n");
scanf("%d",&e);
getchar();
p = (*l).next;
while(p&&(*p).data != e)
{
p = (*p).next;
i ++;
}
if(p == NULL)
printf("爱查查,不查滚\n");
else
printf("The number at %d\n",i);
return 0 ;
} //函数locate()
int insert(node *l) //插入
{
int i; //插入的位置
int e; //插入的值
node *p,*s;
int j = 0;
printf("Please enter the insert location and number:\n");
scanf("%d%d",&i,&e);
getchar();
p = l;
while(p&&j
{
p = (*p).next;
j++;
}
if(!p||j > i - 1)
printf("error\n");
s = (node * )malloc(sizeof(node));
(*s).data = e;
(*s).next = (*p).next;
(*p).next = s ;
PrintList(l);
return 0;
} //函数insert()
int linkdelete(node *l) //删除
{
int i; //删除元素的位置
node * p; //删除元素前一个元素指针
node * q; //删除元素指针
int j = 0;
p = l;
printf("Please enter the location of delete\n");
scanf("%d",&i);
while ((*p).next&&j
{
p = (*p).next;
j++;
}
if(!(*p).next||j > i - 1)
printf("error\n");
q = (*p).next;
(*p).next = (*q).next ;
free (q) ;
PrintList(l);
return 0;
} //函数inkdelete()
int main()
{
node *l ; //定义一个头指针
int n ; //链表含有元素的个数
int k, j;
printf("the length of linklist:");
scanf("%d",&n);
l = createlist(n);
PrintList(l); //输出各元素的值
while(k != 0)
{
k = 1 ;
printf("Please choose\n1.locate 2.insert\n3.delete 4.exit\n");
scanf("%d",&j);
switch(j)
{
case 1 :locate(l) ;break;
case 2 :insert(l) ;break;
case 3 :linkdelete(l);break;
case 4 : k = 0 ;break ;
default : printf("error\n");
}
}
return 0;
}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
