正確代碼
#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int status,Elemtype;
typedef struct LNode{
? ? Elemtype data;//數(shù)據(jù)域
? ? struct LNode *next;//指針域
}LNode,*LinkList;
//函數(shù)聲明
//創(chuàng)建單鏈表
?LinkList CreateList(int n);
?void ShowList();
?LinkList CreateList(int n){
? ? //創(chuàng)建一個空的單鏈表
? LinkList L=(LNode*)malloc(sizeof(LNode));
? L->next=NULL;
//采用后插法進行創(chuàng)建
? LNode *r=L;//初始化尾指針
? int i;
? LNode *p;
? for(i=0;i<n;i++){
? ? ? ? //創(chuàng)建新節(jié)點
? ? p=((LNode*)malloc(sizeof(LNode)));
? ? p->next=NULL;
? ? printf("請輸入第%d個數(shù)據(jù)元素:",i);
? ? scanf("%d",&p->data);
? ? //插入到尾結(jié)點后,成為新的尾結(jié)點
? ? r->next=p;
? ? r=p;
}
? ? printf("單鏈表創(chuàng)建完畢!");
? ? return L;
}
void ShowList(LinkList L){
? ? LNode *p=L->next;
? ? printf("單鏈表為:");
? ? while(p){
? ? ? ? printf("%d ",p->data);
? ? ? ? p=p->next;
? ? }
}
//插入函數(shù)
status ListInsert(LinkList L,int i,Elemtype e){
? ? LNode *p=L;
? ? int j=0;
? ? while(p&&j<j-1){
? ? ? ? p=p->next;
? ? ? ? j++;
? ? }
? ? if(!p||j>i-1){
? ? ? ? printf("插入位置不合法");
? ? ? ? return ERROR;
? ? }
? ? LNode *s=(LNode *)malloc(sizeof(LNode));
? ? s->next=e;
? ? s->next=p->next;
? ? p->next=s;
? ? printf("插入成功,更新后的單鏈表為:");
? ? ShowList(L);
? ? return OK;
}
int main()
{
? ? LinkList L=NULL;
? ? printf("請輸入要創(chuàng)建的單鏈表的長度:");
? ? int n;
? ? scanf("%d",&n);
? ? L=CreateList(n);
? ? ShowList(L);
? ? printf("\n請輸入要插入的位置和值,用空格間隔:");
? ? int i;
? ? Elemtype e;
? ? scanf("%d %d",&i,&e);
? ? ListInsert(L,i,e);
}