还是我先前的那个链表,我又加了几个操作,但在删除操作这一块有点问题,就是不能删除头结点,我仔细检查了语句应该没有发现什么错误,百思不得其解,所以来求助大家。我的代码如下: #define LEN sizeof(struct List) #define OK 1 #define NULL 0 #include "stdlib.h" typedef int ElemType;
/*链表的结构定义*/ struct List{ ElemType elem; struct List *next; };
/*创建一个链表,返回值为head指针*/ struct List *creat(void){ struct List *head; struct List *p1,*p2; p1=p2=(struct List *)malloc(LEN); scanf("%d",&p1->elem); head=NULL; while(p1->elem!=0){ if(head==NULL)head=p1; else p2->next=p1; p2=p1; p1=NULL; p1=(struct List *)malloc(LEN); scanf("%d",&p1->elem); } p2->next=NULL; return(head); }
/*求链表的长度*/ int Length(struct List *L){ struct List *p; int n; p=L;n=1; if(p==NULL)n=0; while(p->next!=NULL){ n=n+1; p=p->next; } return(n); }
/*插入链表元素操作*/ struct List *Insert(struct List *L,int i,ElemType e){ int n; struct List *p,*s; p=L; s=(struct List *)malloc(LEN); if(p==NULL){L=s;s->elem=e;s->next=NULL;} for(n=0;n<i;n++){ if(n==i-1){s->elem=e;s->next=p->next;p->next=s;} p=p->next; } return(L); }
/*删除链表元素操作*/ struct List *Delete(struct List *L,ElemType e){ struct List *p0,*p; if(L==NULL)printf("\nlist is null\n"); p=L; while(e!=p->elem&&p->next!=NULL) {p0=p;p=p->next;} if(e==p->elem){ if(p==L){ L=p->next; } else {p0->next=p->next;} } else printf("%d not been found!\n",e); return(L); }
/*输出链表*/ void print(struct List *head){ struct List *p; printf("The records are:"); p=head; if(head!=NULL) do {printf("%d ",p->elem); p=p->next; }while(p!=NULL); printf("\n"); }
main(){ struct List *L,*head; int i,len; ElemType e1,e2; L=head=creat(); /*创建新链表*/ len=Length(L); /*求链表长度*/ printf("there are %d elems.\n",len); print(head); printf("please input i:\n"); scanf("%d",&i); printf("please input the data you want to insert:\n"); scanf("%dl",&e1); Insert(L,i,e1); len=Length(L); printf("there are %d elems.\n",len); print(head); printf("please input the elem you want to delete:\n"); scanf("%d",&e2); Delete(L,e2); len=Length(L); printf("there are %d elems.\n",len); print(head); }
[此贴子已经被作者于2005-8-9 16:03:58编辑过]