需求:
线性表A、线性表B 都是循环链表存储结构,将B链表链接到A链表的后面,合并成一个链表。
#include<malloc.h>
#include<stdio.h>
typedef struct node{
int data;
struct node *next;
}NODE;
NODE *create_circular(){
NODE *head,*q,*p;
int a,n;
head = (NODE *)malloc(sizeof(NODE));
q = head;
printf("\n Input number of the list:");
scanf("%d",&n);
head ->data = n; /*表头结点赋值n,即表中结点的个数*/
if(n>0){
printf("Input the list:");
while(n>0){
scanf("%d",&a); /*输入新元素*/
p = (NODE *)malloc(sizeof(NODE));
p->data = a;
q->next = p;
q = p;
n--;
}
q->next=head;
return (head);
}
}
//方法需要放在被调用之前
void print(NODE *head){
NODE *p;
p = head->next;
printf("output the list of parame:");
while(p != NULL && p->next!=head){
printf("%3d",p->data);
p=p->next;
}
}
NODE *connect(NODE *head1,NODE *head2){/*把循环列表a和b合并成一个循环链表。head1和head2分别为两个循环列表的头指针*/
NODE *p,*q;
p= head1 ->next; /*指针head1头结点赋值给p*/
// printf("%2d",p->data);
while(p->next!=head1)/*查找head1的最后一个结点*/
p=p->next;
// printf("%2d",p->data); /*此时p为head1最后一个结点*/
q= head2 ->next;
while(q->next!=head2)/*查找head2的最后一个结点*/
q=q->next;
p->next = head2->next; /*AB两表链接*/
q->next = head1;
free(head2);/*释放B表表头结点*/
return(head1);
}
main(){
NODE *a,*b,*c,*d;
a = create_circular();
b = create_circular();
c= connect(a,b);
d = c;
printf("\n Output the list"); /*输出链表后的整个链表*/
while(d->next !=c){
d = d->next;
printf("%3d",d->data);
}
}