合并两个有序单链表的递归方法

来源:互联网 发布:织田信忠 知乎 编辑:程序博客网 时间:2024/06/07 02:38

#include<stdio.h>#include<stdlib.h>typedef int datatype;typedef struct node{datatype data;struct node*next;}circlelist;circlelist* create(){circlelist*l = (circlelist*)malloc(sizeof(circlelist));l->next = NULL;//l->data = -1;return l;}int insert(circlelist*l,datatype value){circlelist*temp = (circlelist*)malloc(sizeof(circlelist));    temp->data = value;temp->next = l->next;l->next = temp;return 0;}int show(circlelist*l){   //circlelist*p = l;while(l->next != NULL){l = l->next;printf("%d",l->data);}return 0;}int show_merge(circlelist*l){   //circlelist*p = l;while(l->next != NULL){printf("%d",l->data);l = l->next;}printf("%d",l->data);return 0;}circlelist* del_head(circlelist*l){circlelist*p = l->next;//l = p->next;//while(l->next != NULL)//l = l->next;//free(p);//p = NULL;l = p;return l;}int show2(circlelist*l){ circlelist*p = l;while(l->next != p){l = l->next;printf("%d",l->data);}return 1;}int joseph(int n,int m,int k){int i = 0;circlelist*l = create();for(i=n;i>0;i--){insert(l,i);}l = del_head(l);//circlelist*p = l;for(i=1;i<k;i++){l = l->next;}while(l->next != l){for(i=1;i<m-1;i++)l = l->next;circlelist*temp = l->next;l->next = temp->next;printf("%d",temp->data);l = l->next;//free(temp);//temp = NULL;}printf("%d",l->data);//free(l);//l=NULL;return 0;}circlelist*merge_sort(circlelist*h1,circlelist*h2){circlelist*head = NULL;if(h1 == NULL)return h2;if(h2 == NULL)return h1;if(h1->data<h2->data){head = h1;head->next = merge_sort(h1->next,h2);}else{head = h2;head->next = merge_sort(h1,h2->next);}return head;}int main(int argc,const char*argv[]){circlelist*h1 = create();circlelist*h2 = create();insert(h1,7);insert(h1,5);insert(h1,3);insert(h1,1);show(h1);circlelist*p = del_head(h1);printf("\n");show_merge(p);printf("\n");insert(h2,8);insert(h2,6);insert(h2,4);insert(h2,2);show(h2);printf("\n");circlelist*q = del_head(h2);show_merge(q);printf("\n");circlelist*s = merge_sort(p,q);show_merge(s);//joseph(8,4,3);return 0;}

递归合并总体思想比较两个链表第一个节点,将最小的节点作为合并后头结点,然后将最小节点那个链表下一个节点继续与另一条链表比较找到下一个最小节点并插入到后面。

由于单链表存在头结点需要去头,并且打印函数show和show_merge有点区别,去头之后的打印函数最后需要再打印一下数据。




0 0