使用C语言对数据结构的合并列表排序的示例代码

电脑杂谈  发布时间:2020-04-15 12:08:14  来源:网络整理

约瑟夫问题 c语言链表_c语言单链表排序_c语言 链表

更新时间: 2017年5月25日14:16:18作者: cursive-Paradis

约瑟夫问题 c语言链表_c语言单链表排序_c语言 链表

本文主要介绍用C语言编写的数据结构链接列表的合并排序示例代码的相关信息. 需要它的朋友可以参考它

约瑟夫问题 c语言链表_c语言单链表排序_c语言 链表

使用C语言对数据结构的合并列表排序的示例代码

c语言单链表排序_约瑟夫问题 c语言链表_c语言 链表

问题

约瑟夫问题 c语言链表_c语言 链表_c语言单链表排序

具有两个无头节点的单个链表,头指针分别是ha和hb,链中有数据字段data,接下来是链接域,两个链表的数据以升序存储. 到ha表中,并且ha在合并后仍按升序排列. 如果合并时ha表中的数据也位于hb中c语言单链表排序c语言单链表排序,则该hb中的数据不会合并到ha中,并且该算法中不允许破坏hb的链表.

源程序

#include <stdio.h> 
#include<stdlib.h> 
#define N1 6 /*链表La的长度*/  
#define N2 6 /*链表Lb的长度*/ 
struct listnode  
{ 
 int data; 
 struct listnode *next; 
}; 
void createlist(struct listnode * *,int);  
void listinsert(struct listnode * *,struct listnode * *); 
void readlist(struct listnode *); 
int main() 
{ 
  
 struct listnode *ha=NULL,*hb=NULL; 
 printf("请按照升序序列输入以下数字以建立链表La\n"); 
 printf("Please Input %d numbers:",N1); 
 createlist(&ha,N1); 
 printf("请按照升序序列输入以下数字以建立链表Lb\n"); 
 printf("Please Input %d numbers:",N2); 
 createlist(&hb,N2); 
 listinsert(&ha,&hb); 
 readlist(ha); 
 printf("\n");  
} 
 
 
void createlist(struct listnode * *p,int n) 
{ /*尾插法建立链表*/ 
 struct listnode *t,*q; 
 int i; 
 t=(struct listnode *)malloc(sizeof(struct listnode)); 
 scanf("%d",&t->data); 
 *p=t; 
 q=t;  
 for(i=n-1;i>0;i--) 
    { 
 t=(struct listnode *)malloc(sizeof(struct listnode)); 
 scanf("%d",&t->data); 
 q->next=t; 
 q=t; 
  } 
 q->next=NULL; 
} 
 
void listinsert(struct listnode * *a,struct listnode * *b)  
{ /*将两个链表按递增序列排序*/ 
 struct listnode *pa,*pb,*other,*la,*pre; 
 la=(struct listnode *)malloc(sizeof(struct listnode)); 
 la->next=*a; 
 pa=*a;    
 pb=*b; 
 pre=la;   
 while(pa&&pb) 
  { 
 if(pa->data<pb->data) 
   {   
  pre=pre->next; 
  pa=pa->next; 
  } 
 else if (pa->data>pb->data) 
 { 
  other=(struct listnode *)malloc(sizeof(struct listnode)); 
  other->data=pb->data; 
  other->next=pa; 
  pre->next=other; 
  pre=other; 
  pb=pb->next; 
   } 
  
 else 
 { 
  pre=pre->next; 
  pa=pa->next; 
  pb=pb->next; 
  } 
 } 
  
 if(!pa) 
 { 
 while(pb) 
 { 
  other=(struct listnode *)malloc(sizeof(struct listnode)); 
  other->data=pb->data;   
        pre->next=other; 
  pre=pre->next; 
  pb=pb->next; 
 } 
 pre->next=NULL; 
 } 
 *a=la->next; 
 free(la); 
} 
 
void readlist(struct listnode *p) 
{ /*遍历链表并输出最终结果*/ 
 struct listnode *q; 
 q=p; 
 printf("链表的排序结果为:\n"); 
 while(q!=NULL) 
   { 
 printf("%3d",q->data); 
 q=q->next; 
 } 
 printf("\n"); 
} 

运行结果


本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/jisuanjixue/article-176500-1.html

    相关阅读
      发表评论  请自觉遵守互联网相关的政策法规,严禁发布、暴力、反动的言论

      热点图片
      拼命载入中...