题目描述
设非空线性ha和hb都用带头结点的循环双链表表示。设计一个算法Insert(ha,hb,i)。其功能是:i=0时,将线性表hb插入到线性表ha的最前面;当i>0时,将线性表hb插入到线性表ha中的第i个结点的后面;当i大于等于线性表ha的长度时,将线性表hb插入到线性表ha的最后面。
完整源代码如下:
#include<stdio.h>
#include<stdlib.h>
typedef struct DNode
{
int data;
struct DNode *next;
struct DNode *prior;
}DLinkNode;
void Init(DLinkNode *&L)
{
L=(DLinkNode *)malloc(sizeof(DLinkNode));
L->next = NULL;
L->prior = NULL;
}
void Creat(DLinkNode *&L,int a[],int n)
{
DLinkNode *p,*r=L;
int i;
for(i=0;i<n;i++)
{
p=(DLinkNode *)malloc(sizeof(DLinkNode));
p->data = a[i];
r->next = p;
p->prior = r;
r = p;
}
r->next = L;
}
void Insert(DLinkNode *&ha,DLinkNode *&hb,int i)
{
DLinkNode *p=ha,*q,*pre;
int length=0,j;
while(p->next!=ha)
{
p=p->next;
length++;
}
printf("length:%d\n",length);
if(i>=length) //把hb插入到ha的结尾
{
p->next = hb->next;
hb->next->prior = p;
q = hb;
while(q->next != hb)
q = q->next;
q->next = ha;
}
else if(i==0) //把表hb插入到ha的开头
{
q = hb;
while(q->next != hb)
q = q->next;
q->next = ha->next;
ha->next->prior = q;
p->next = hb;
ha = hb;
}
else //把hb插入到ha中第i个元素的后面
{
p = ha;
for(j = 0;j < i;j++)
{
p = p->next;
}
pre = p->next;
q = hb;
while(q->next != hb)
q = q->next;
q->next = pre;
pre->prior = q;
p->next = hb->next;
hb->next->prior = p;
}
}
void Print(DLinkNode *L)
{
DLinkNode *p=L->next;
while(p != L)
{
printf("%d ",p->data);
p=p->next;
}
printf("\n");
}
int main()
{
DLinkNode *ha,*hb;
int a[10]={1,2,3,4,5,6,7,8,9,10};
int b[10]={11,12,13,14,15,16,17,18,19,20};
Init(ha);
Init(hb);
Creat(ha,a,10);
Creat(hb,b,10);
Insert(ha,hb,2);
Print(ha);
return 0;
}