c语言 顺序表、链表的归并merge操作

顺序表的归并操作:

void merge(int* a, int m, int* b, int n, int* c) {
	int i = 0, j = 0;
	int k = 0;
	while (i < m && j < n) {
		if (a[i] < b[j])
			c[k++] = a[i++];
		else    c[k++] = b[j++];
	}
	while (i < m) {
		c[k++] = a[i++];
	}
	while (j < n) {
		c[k++] = b[j++];
	}
}

int main() {
	seqlist a;
	a.length = 5;
	a.data[0] = 0;
	a.data[1] = 2;
	a.data[2] = 3;
	a.data[3] = 5;
	a.data[4] = 7;

	seqlist b;
	b.length = 3;
	b.data[0] = 1;
	b.data[1] = 4;
	b.data[2] = 6;

	seqlist t;
	t.length = a.length + b.length;	//记得赋值!!!
	
    merge(a.data, a.length, b.data, b.length, t.data);
	printf("merging..............");
	for (int i = 0; i < t.length; i++) {
		printf("t[%d]=%d\n", i, t.data[i]);
	}
	


}

单链表的归并操作: 

 

LinkList merge(LinkList A, LinkList B, LinkList C) {
	LinkList p = A->next;
	LinkList q = B->next;
	LinkList r;
	/*C需要有头结点,将A或B的头结点给C*/
	C = A;
	C->next = NULL;
	free(B);
	r = C;
	while (p && q) {
		if (p->data < q->data) {
			r->next = p;
			r = r->next;
			p = p->next;
		}
		else {
			r->next = q;
			r = r->next;
			q = q->next;
		}
  	}
	while (p) {
		r->next = p;
		break;    //break操作???
	}
	while (q) {
		r->next = q;
		break;    //break操作???
	}
	return C;     //返回指针!!!
}

/* 1 3 -1 2 4 5 -1 */
int main() {
	Node m;
	LinkList p = createNode(&m);
	Node n;
	LinkList q = createNode(&n);
	printf("merging......\n");

	LinkList r;
	r = (LinkList)malloc(sizeof(Node));    //初始化r
	r=merge(p, q, r);
	printN(r);

	return 0;
}

 

你可能感兴趣的:(数据结构)