生成结点值互不相同的且递增有序的单链表

来源:互联网 发布:linux查看系统版本 编辑:程序博客网 时间:2024/05/16 16:18

   ListSort算法的原理:对原串从左到右扫描,每扫描到一个结点,就生成一个新结点,并使新结的数据域值等于当前扫描到的结点的数据域值,然后将新结点按序插入到新的链表中,并释放原结点,然后继续扫描,重复上述操作,直到扫描完原链表为止。此时就生成一个新的有序链表,原链表的内存空间被完全释放。

#include<stdio.h>#include<stdlib.h>#include<malloc.h>#include<conio.h>#include<time.h>typedef struct LNode//链表结点结构的定义{int data;struct LNode *next;}LNode,*LinkList;int DisplayList(LinkList head)//输出链表中的数据域的值{if(head==NULL){printf("链表为空!\n");return 0;}LinkList p=head;while(p->next!=NULL){printf("%5d ->",p->data);p=p->next;}printf("%5d",p->data);//输出最后一个数据printf("\n\n");return 0;}int CreateList(LinkList &head)//生成链表的函数定义{int i=0;LinkList p=NULL,q=NULL;head=NULL;srand( (unsigned)time( NULL ) );for(i=0;i<30;i++){p=(LinkList)malloc(sizeof(LNode));p->data=rand()%100*7;if(head==NULL)head=p;elseq->next=p;q=p;}if(head!=NULL){q->next=NULL;}return 1;}LinkList ListSort(LinkList head)//对链表的结点按数据域的大小从小到大排序{if(head==NULL || head->next==NULL)return head;else{LinkList pre,lp,p,q,s;pre=head;q=p=pre->next;head->next=NULL;while(p!=NULL){s=(LinkList)malloc(sizeof(LNode));s->data=q->data;s->next=NULL;p=p->next;free(q);q=p;//记得释放原结点if(s->data < head->data){s->next=head;head=s;}else{pre=head;lp=pre->next;while(lp!=NULL && s->data > lp->data)if(s->data > lp->data){pre=lp;lp=lp->next;}s->next=lp;pre->next=s;}}return head;}}int DelrepetElem(LinkList head)//删除链表中重复的结点(即数据域相同的结点只留下一个){LinkList pre=head,lp;if(pre!=NULL){while(pre->next!=NULL)if(pre->data != pre->next->data)pre=pre->next;else{lp=pre->next;pre->next=lp->next;free(lp);}}return 1;}void main(){LinkList head,headla;CreateList(head);//生成链表laprintf("初始生成时链表la的数据为:\n");DisplayList(head);headla=ListSort(head);printf("经排序后的链表la的数据为:\n");DisplayList(headla);DelrepetElem(headla);printf("经排序且删除相同元素后的链表la的数据为:\n");DisplayList(headla);printf("\n");}


 

原创粉丝点击