思路:
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;
}