39-19
设有有一个带头结点的循环单链表,反复找出单链表中最小的结点并删除,直至链表为空
注意删除需要释放空间,包括释放最后的链表头结点
#include <stdio.h> #include <stdlib.h> typedef struct node{ int data; struct node *next; }LNode,*LinkList; void CreateList(LinkList &L) { L=(LinkList)malloc(sizeof(LNode)); L->next=NULL; LNode *p=L; int x; scanf("%d",&x); while(x!=999) { LNode *node=(LNode*)malloc(sizeof(LNode)); node->data=x; node->next=NULL; p->next=node; p=node; scanf("%d",&x); } p->next=L; } void displayList(LinkList L) { LNode *p=L->next; while(p!=L) { printf("%d ",p->data); p=p->next; } } void Delete(LinkList &L) { LNode *p,*r,*min,*minpre; while(L->next!=L) { p=L->next;r=L; min=p;minpre=r; while(p!=L) { if(p->data<min->data) { min=p; minpre=r; } else { r=p; p=p->next; } } printf("%d ",min->data); minpre->next=min->next; free(min); } free(L); } int main() { LinkList L; CreateList(L); displayList(L); printf("\n"); Delete(L); return 0; }