天天看點

兩個循環鍊合并

思路:

1、寫循環鍊結構;

2、寫兩個循環鍊合并操作。

#include <iostream>
using namespace std;
#include <stdlib.h>

typedef struct cyclink {
	int data;
	struct cyclink *next;
	//struct cyclink *head;
}cyclink,*link;

void create_cyclink(link &h,int num) {
	int i;
	link p,s;

	//p = l;
	h = (link)malloc(sizeof(cyclink));
	p = h;
	h ->data = num;
	//l ->next = l;

	for(i = 0;i < num;i++) {
		
		s = (link)malloc(sizeof(cyclink));
	
		cin >> s ->data;
		p ->next = s;
		p = s;
	}
	//h = h ->next;
	p ->next = h;
//	h = h ->next;

/*	l ->next = l;

	for(i = num;i > 0; --i) {
		p = (link)malloc(sizeof(cyclink));
		cin>> p ->data;
		p ->next = l ->next;
		l ->next = p;
	}
*/
}


void cat_link(link &lc,link la,link lb) {
	link ha,hb,hc;
	int length;
	ha = la;
	hb = lb;
	length = (ha ->data) + (hb ->data);

	while(lb ->next != hb) lb = lb ->next;
	//lb = lb ->next;
	lb ->next = ha;

	while(la ->next != ha) la = la ->next;
	hb = hb ->next;
	la ->next = hb;

	lc = (link)malloc(sizeof(cyclink));
	hc = lc;
	lc ->data = length;
	while(la ->next != ha) la = la ->next;
	hc = la ->next;
	lc = hc;

}

void print_cyclink(link l) {
	link h;
	h = l;
	while(l ->next != h ) {
		l = l ->next;
		cout << l ->data<<", ";
	}
	
}

int main() {
	int i;
	link la,lb,lc;

	cout<<"num1 = ";
    cin>>i;

	create_cyclink(la,i);
	print_cyclink(la);
	cout<<endl;

	cout<<"num2 = ";
    cin>>i;

	create_cyclink(lb,i);
	print_cyclink(lb);
	cout<<endl;

	cat_link(lc,la,lb);
	print_cyclink(lc);

	free(lc);
	free(lb);
	free(la);
	while(1);
	return 0;
}
           

執行結果圖:

兩個循環鍊合并

總結:

此程式還有一些問題存在,

就是到最後列印合并後鍊的時候,

程式執行有問題,但是結果不影響。

這個問題要想想是不是搜尋過頭!~

修改:

兩個鍊并聯函數,備援有一個鍊。

删減一個

#include <iostream>
using namespace std;
#include <stdlib.h>

typedef struct cyclink {
	int data;
	struct cyclink *next;
}cyclink,*link;

void create_cyclink(link &h,int num) {
	int i;
	link p,s;

	h = (link)malloc(sizeof(cyclink));
	p = h;

	for(i = 0;i < num;i++) {
		
		s = (link)malloc(sizeof(cyclink));
	
		cin >> s ->data;
		p ->next = s;
		p = s;
	}
	p ->next = h;

}


void cat_link(link &la,link &lb) {
	link ha,hb;
	int length;
	ha = la;
	hb = lb;

	while(lb ->next != hb) lb = lb ->next;
	lb ->next = ha;

	while(la ->next != ha) la = la ->next;
	hb = hb ->next;
	la ->next = hb;

	while(la ->next != ha) la = la ->next;
	la = la ->next;

}

void print_cyclink(link l) {
	link h;
	h = l;
	while(l ->next != h ) {
		l = l ->next;
		cout << l ->data<<", ";
	}
	
}

int main() {
	int i;
	link la,lb;

	cout<<"num1 = ";
    cin>>i;

	create_cyclink(la,i);
	print_cyclink(la);
	cout<<endl;

	cout<<"num2 = ";
    cin>>i;

	create_cyclink(lb,i);
	print_cyclink(lb);
	cout<<endl;

	cat_link(la,lb);
	print_cyclink(la);


	free(lb);
	free(la);
	while(1);
	return 0;
}
           

繼續閱讀