[作业]两个有序表合并为一个有序表

[作业]两个有序表合并为一个有序表

#include "stdio.h"
#include "malloc.h"
typedef struct LNode {
	int data;
	struct LNode *next;
}LNode, *LinkList;

LNode* InitLList_step(int low, int up,int step) {  //创建步长为step的有序链表
	LNode *head, *s, *r;	//head,r 头,尾
	head = (LNode *)malloc(sizeof(LNode));
	r = (LNode *)malloc(sizeof(LNode));
	head->data = 9527;
	head->next = r;			//设置head结点成员
	r->data = low;
	r->next = NULL;			//设置r结点成员
	for (int i = low + step; i <= up;) {
		s = (LNode *)malloc(sizeof(LNode));
		s->data = i;		//i==>s.data
		s->next = r->next;	//s.next --> r.next == NULL ,设置链表末尾指针为空
		r->next = s;		//r.next --> s 的地址
		r = s;				//s为临时变量,最后链表末尾替换为r
		i=i + step;
	}
	return head;
} //InitLList_step

void PrintLList(LNode* l) {	//传入参数l为该链表的head
	LNode* s;
	s = l->next;		//s = 链表 head.next 为指针
	while (s) {			//保证s不是链表末尾 即 地址s存在
		printf("%d\t", s->data);
		s = s->next;	//s指针后移,依次打印
	}printf("\n");
} //PrintLList

LNode* MergeLList(LNode* l1, LNode* l2) { //合并顺序链表
	LNode *head, *s, *r;	//head,r 头,尾
	LNode* s1, *s2;
	head = (LNode *)malloc(sizeof(LNode));
	r = (LNode *)malloc(sizeof(LNode));
	head->data = 9527;
	head->next = r;			//设置head结点成员

	s1 = l1->next;			//s = 链表 head.next 为指针
	s2 = l2->next;
	if (s1->data < s2->data){
		r->data = s1->data;
		r->next = NULL;		//设置r结点成员
		s1 = s1->next;		//s指针后移
	}else {
		r->data = s2->data;
		r->next = NULL;
		s2 = s2->next;
	}
	while (s1 && s2) {		//循环到末尾
		if (s1->data < s2->data){
			s = (LNode *)malloc(sizeof(LNode));
			s->data = s1->data;	//s1.data ==>s.data
			s->next = r->next;	//s.next --> r.next == NULL ,设置链表末尾指针为空
			r->next = s;		//r.next --> s 的地址
			r = s;				//s为临时变量,最后链表末尾替换为r
			s1 = s1->next;		//s1指针后移
		}else {
			s = (LNode *)malloc(sizeof(LNode));
			s->data = s2->data;
			s->next = r->next;
			r->next = s;
			r = s;
			s2 = s2->next;
		}
	}
	if (s1){ s->next = s1; } //谁没到末尾 则继续连接谁
	else { s->next = s2; }

	return head;
} // MergeLList

int main() {
	LNode* L1,*L2,*LL;
	printf("创建顺序链表: \n");
	L1 = InitLList_step(1, 10, 2); //创建链表并返回该链表的head给L1
	PrintLList(L1);
	L2 = InitLList_step(2, 20, 4);
	PrintLList(L2);
	printf("合并顺序链表: \n");
	LL = MergeLList(L1, L2);
	PrintLList(LL);
}

你可能感兴趣的:([作业]两个有序表合并为一个有序表)