//单链表的插入与删除 #include #include typedef struct node { char data; struct node *next; }LNode; //创建单链表 LNode *create() { LNode *head,*p,*q; char x; head=(LNode*)malloc(sizeof(LNode)); head->next=NULL; p=head; q=p; printf("请输入数据: \n"); scanf("%c",&x); while(x!='\n') { p=(LNode*)malloc(sizeof(LNode)); p->data=x; p->next=NULL; q->next=p; q=p; scanf("%c",&x); } return head; } //1 输出单链表 void print(LNode*head) { LNode*p=head->next; while(p!=NULL) { printf("%c->",p->data); p=p->next; } printf("\n"); } // 2在第i个位置插入结点x LNode *insert(LNode*head,int i,char x) { LNode *p=head,*s; int j=0; while(p!=NULL&&jnext; j++; } if(p==NULL) printf("False\n"); else { s=(LNode*)malloc(sizeof(LNode)); s->data=x; s->next=p->next; p->next=s; } return head; } // 3删除第i个结点 LNode *del(LNode *head,int i) { LNode *p=head,*s; int j=0; while(p!=NULL&&jnext; j++; } if(p==NULL) printf("False\n"); else { s=p->next; p->next=s->next; free(s); } return head; } int main() { LNode *h; h=create(); print(h); int i; char x; printf("输入要插入的位置i和值x:(用逗号隔开)\n"); scanf("%d,%c",&i,&x); insert(h,i,x); print(h); printf("输入要删除的结点的位置i:\n"); scanf("%d",&i); del(h,i); print(h); return 0; }