代码问题在于递归调用delmaxnode函数时没有判断链表是否为空,导致程序陷入死循环。修改后的代码如下:

#include<stdio.h> #include<malloc.h>

typedef int ElemType; typedef struct LNode { ElemType data; struct LNode *next; }LinkNode;

void delmaxnode(LinkNode *&L) { LinkNode *p=L->next,*pre=L,*maxp=p,*maxpre=pre; while(p!=NULL){ if(maxp->datadata) { maxp=p; maxpre=pre; } else if(maxp->data==p->data){
maxpre=p; } pre=p; p=p->next; } maxpre->next=maxp->next; free(maxp); if(L->next!=NULL) // 判断链表是否为空 delmaxnode(L);
}

bool ListInsert(LinkNode *&L,int i,ElemType e) { int j=0; LinkNode *p=L,*s; if(i<=0) return false; while(j<i-1&&p!=NULL){ j++; p=p->next; } if(p==NULL&&j<i-1) return false; else { s=(LinkNode *)malloc(sizeof(LinkNode)); s->data=e; s->next=p->next; p->next=s; return true; } }

void DispList(LinkNode *L) { LinkNode *p=L->next; while(p!=NULL){ printf("%d ",p->data); p=p->next; } printf("\n"); }

void InitList(LinkNode *&L) { L=(LinkNode *)malloc(sizeof(LinkNode)); L->next=NULL; }

int main(){ LinkNode *L; InitList(L); ListInsert(L,1,7); ListInsert(L,2,9); ListInsert(L,3,8); ListInsert(L,4,5); ListInsert(L,5,4); ListInsert(L,6,9); DispList(L); delmaxnode(L); DispList(L); return 0;

#includestdioh#includemallochtypedef int ElemType;typedef struct LNode ElemType data; struct LNode next;LinkNode;void delmaxnodeLinkNode &L LinkNode p=L-nextpre=Lmaxp=pmaxpre=pre; whilep

原文地址: https://www.cveoy.top/t/topic/f4Sw 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录