链表操作,问题在哪里呢?
//动态链表操作#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 30
//链表结构的声明
typedef struct name
{
char name[MAX];
struct name *link;
}NAME;
NAME *head;
int n;
//创建链表
NAME *creat_link_list(int n)
{
NAME *p,*q;
int i=1;
printf("'We will creat a link for you \n");
p = (NAME *)malloc(sizeof(NAME));
head = p;
for(;i<n;i++)
{
scanf("%s",p->name);
q = (NAME *)malloc(sizeof(NAME));
q->link = p;
p = q;
}
scanf("%s",p->name);
p->link = NULL;
//getchar();
return (head);
}
//链表插入函数
NAME *input_link_list(char name[MAX],int x)
{
NAME *p,*q;
int i=1;
p=(NAME*)malloc(sizeof(NAME));
strcpy(p->name,name);
if(x==1)
{
p->link = head;
head = p;
}
else if(x<1 || x>n)
{
printf("\nError!The location is wrong!\n");
exit (1);
}
else
{
q = head;
for(;i<x;i++) //找x的位置
q = q->link;
p->link = q->link;//插入
q->link = p;
}
return (head);
}
//链表元素删除函数
NAME *cut_link_list(int x)
{
NAME *p,*q;
int i=1;
q = head;
if(x<1 || x>n)
{
printf("You have told a wrong location !\n");
exit (1);
}
if(x==1)
{
p = head;
free(head);
head = p->link;
}
if(x>1 || x <=n)
{
for(;i<x;i++) //以找到删除元素的位置。
q = q->link;
p = q->link;
q->link = p->link;
free(p);
}
return (head);
}
//链表打印函数自定义。
int print(NAME *head)
{
NAME *p;
p = head;
printf("This is it\n");
while(p != NULL)
{
printf("%s",p->name);
p = p->link;
}
printf("\n");
return 1;
}
//主函数已测试所有的应用函数
int main()
{
int m,k;
char name2[MAX];
printf("\nPlease enter the n to define the structlink :\n");
scanf("%d",&n);
creat_link_list(n);
if(print(head))
{
printf("Enter the name you want to add and the m which is the location:\n");
scanf("%s %d",name2,&m);
input_link_list(name2,m);
if(print(head))
{
printf("Enter the k which is the location:\n");
scanf("%d",&k);
cut_link_list(k);
print(head);
}
}
}