#include<stdio.h>
#include<stdlib.h>
typedef struct list{
char data;
struct list* next;
}*List,L;
List newList();
void showList(List head);
void insert(List head, int i, char X);
int main()
{
//初始化链表
char ch;
char insertNum;
int insertPlace;
List head = newList();
showList(head);
printf("\n");
//在链表asdfghjkl的第四个位置插入z
printf("***********************\n");
printf("下面是插入操作\n");
printf("请输入你要插入的位置:\n");
scanf("%d",&insertPlace);
//清空缓冲区
while(ch=getchar() != '\n');
printf("请输入你插入的数:\n");
scanf("%c",&insertNum);
insert(head,insertPlace,insertNum);
showList(head);
return 0;
}
List newList()
{
List head = (List)malloc(sizeof(L));
List p;
head->next=NULL;
p=head;
while(1)
{
char i;
char ch;
printf("请输入一个字符:\n");
printf("如果要退出,则输入1:\n");
scanf("%c", &i);
if(i == '1')
break;
// 数据加入
List node = (List)malloc(sizeof(L));
node->data = i;
node->next = NULL;
p->next = node;
p = node;
//清空缓冲区
while(ch=getchar() != '\n');
}
return head;
}
//打印链表内容
void showList(List head)
{
List p;
p=head->next;
while(p != NULL)
{
printf("%c",p->data);
p = p->next;
}
}
void insert(List head, int i, char X)
{
//插入opt
List p, q;
int count = 1;
List node = (List)malloc(sizeof(L));
p = head -> next;
q = head;
//位置分析
if(i<1)
{
printf("不能插在这\n");
return;
}
//insert operator
while(p!=NULL)
{
if(count<i)
{
q = p;
p = p->next;
count++;
}
else
break;
}
if(p==NULL)
{
printf("没有这个位置\n");
return;
}
//节点插入
node->data = X;
node->next=p;
q->next=node;
}