Merge sorted linked lists

#include <stdio.h>

struct node {
	int data;
	struct node *next;
};

void info(struct node *p) {
	if (p == NULL) {
		printf("merge result is NULL");
	}
	while (p != NULL) {
		printf("%d ", p->data);
		p = p->next;
	}
	printf("\n");
}

struct node* merge_r(struct node *l, struct node *m, struct node *tail) {
	if (l != NULL && m != NULL) {
		if (l->data < m->data) {
			tail->next = l;
			merge_r(l->next, m, tail->next);
		} else {
			tail->next = m;
			merge_r(l, m->next, tail->next);
		}
	} else if (l != NULL) {
		tail->next = l;
	} else if (m != NULL) {
		tail->next = m;
	} else {
		tail->next = NULL;
	}
}

/*
 * use recursion.
 */
struct node* merge1(struct node *l, struct node *m) {
	struct node head;
	head.data = 0; head.next = NULL;
	merge_r(l, m, &head);
	return head.next;
}

/*
 * without the use of recursion.
 */
struct node* merge(struct node *l, struct node *m) {
	struct node *head = NULL;
	struct node *tail = NULL;
	struct node *cur;
	int no;

	while (l != NULL && m != NULL) {
		if (l->data < m->data) {
			cur = l; no = 1;
		} else {
			cur = m; no = 2;
		}
		if (head == NULL)
			head = cur;
		if (tail == NULL)
			tail = cur;
		else {
			tail->next = cur;
			tail = tail->next;
		}
		switch (no) {
			case 1:
				l = l->next; break;
			case 2:
				m = m->next; break;
			default:
				/* impossible */
				break;
		}
	}	

	if (l != NULL) 
		if (tail == NULL)
			head = l;
		else
			tail->next = l;
	if (m != NULL) 
		if (tail == NULL)
			head = m;
		else
			tail->next = m;
	return head;
}

void test1() {
	printf("=== test1 \n");
	struct node l1, l2, m1, m2, m3;

	l1.data = 2; l1.next = &l2;
	l2.data = 7; l2.next = NULL;

	m1.data = 1; m1.next = &m2;
	m2.data = 10; m2.next = &m3;
	m3.data = 11; m3.next = NULL;

	struct node *result = merge(&l1, &m1);
	info(result);
}

void test2() {
	printf("=== test2 \n");
	struct node *result;
	result = merge(NULL, NULL);
	info(result);
}

void test3() {
	printf("=== test3 \n");
	struct node l1, l2;

	l1.data = 2; l1.next = &l2;
	l2.data = 7; l2.next = NULL;

	info(merge(&l1, NULL));
}

void test4() {
	printf("=== test3 \n");
	struct node m1, m2, m3;

	m1.data = 1; m1.next = &m2;
	m2.data = 10; m2.next = &m3;
	m3.data = 11; m3.next = NULL;

	struct node *result = merge(NULL, &m1);
	info(result);
}

int main(int argc, const char *argv[]) {
	test1();
	test2();
	test3();
	test4();
	return 0;
}
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值