#include<stdio.h>
#include<stdlib.h>
typedef struct Link{
int elem;
struct Link *next;
}link;
link *create(){
link *head, *p, *tail;
int count, i;
printf("请输入数据总数:");
scanf("%d", &count);
if(count<0){
printf("错误,总数不应该小于0\n");
exit(1);
}
head=(Link*)malloc(sizeof(Link));
head->next=NULL;
tail=head;
for(i=0; i<count;i++)
{
p=(Link*)malloc(sizeof(Link));
printf("工号:");
scanf("%d", &p->elem);
p->next=NULL;
tail->next=p;
tail=p;
}
printf("链表创建成功!\n");
return head;
}
void print(Link *head){
int len=0;
Link *p=head->next;
while(p){
printf("%d\n",p->elem);
p=p->next;
//通过链表遍历,用len记录链表长度 ,并传入到head结点的数据域中
len++;
}
head->elem=len;
printf("数据总数:%d\n",head->elem);
}
Link *insertLink(Link *head){
Link *node=(Link*)malloc(sizeof(Link));
int k=0;
int count;
printf("请输入要插入的数据的信息(工号):\n");
scanf("%d", &node->elem);
printf("请输入插入第几号元素前(如果要把信息方法链表最后面,输入的位置应该为数据总数+1):");
scanf("%d", &count);
if(count<=0){
printf("输入不合法\n");
exit(1);
}
Link *p=head->next,*pre=head;
//思考 k<=count-1 的作用
while(p!=NULL && k<=count-1){
if( ++k > count-1 ){
break;
}
pre=pre->next;
}
node->next=pre->next;
pre->next=node;
return head;
}
Link *outsertLink(Link *head){
Link *node=(Link*)malloc(sizeof(Link));
int k=0;
int count;
printf("请输入要插入的数据的信息(工号):\n");
scanf("%d", &node->elem);
printf("请输入插入第几号元素后:(如果想把数据放到链表最前面,输入的位置为0)");
scanf("%d", &count);
if(count<0){
printf("输入不合法\n");
exit(1);
}
Link *p=head->next,*pre=head;
//思考 k<=count 的作用
while(p!=NULL && k<=count){
if( ++k > count ){
break;
}
pre=pre->next;
}
node->next=pre->next;
pre->next=node;
return head;
}
Link *choices(Link *head){
int choice;
printf("请选择前插法(1)或后插法(2):");
scanf("%d", &choice);
switch(choice){
case 1:insertLink(head);break;
case 2:outsertLink(head);break;
default:printf("输入不合法\n"); exit(1);
}
}
int main(){
Link *head=NULL;
head=create();
print(head);
head=choices(head);
print(head);
return 0;
}