問題及代碼:
/*
Copyright (c)2015,煙臺大學計算機與控制工程學院
All rights reserved.
文件名稱:第4周項目5--循環雙鏈表應用.cpp
作 者:朱振華
完成日期:2015年10月9日
版 本 號:v1.0
問題描述:設非空線性表ha和hb都用帶頭節點的循環雙鏈表表示。設計一個算法Insert(ha,hb,i)。
其功能是:i=0時,將線性表hb插入到線性表ha的最前面;當i>0時,
將線性表hb插入到線性表ha中第i個節點的後面;當i大於等於線性表ha的長度時,
將線性表hb插入到線性表ha的最後面。
請在實現算法時,除項目中給出的特殊要求,其餘工作均可利用項目4完成的算法支持。
輸入描述:若干數據。
程序輸出:ha的數據hb的數據及按照題目排好序後的新鏈表。
*/
#include <stdio.h>
#include <malloc.h>
#include "cdlinklist.h"
void Insert(CDLinkList *&ha, CDLinkList *&hb,int i)
{
CDLinkList *p=ha->next,*q;
int lena=1,j=1;
while (p->next!=ha) //求出ha的長度lena
{
lena++;
p=p->next;
}
if (i==0) //將hb的所有數據結點插入到ha的頭結點和第1個數據結點之間
{
p=hb->prior; //p指向hb的最後一個結點/
p->next=ha->next; //將*p鏈到ha的第1個數據結點前面
ha->next->prior=p;
ha->next=hb->next;
hb->next->prior=ha; //將ha頭結點與hb的第1個數據結點鏈起來
}
else if (i<lena) //將hb插入到ha中間
{
p=ha->next;
while (j<i) //在ha中查找第i個結點*p
{
j++;
p=p->next;
}
q=p->next; //q指向*p結點的後繼結點/
p->next=hb->next; //hb->prior指向hb的最後一個結點
hb->next->prior=p;
hb->prior->next=q;
q->prior=hb->prior;
}
else //將hb鏈到ha之後
{
ha->prior->next=hb->next; //ha->prior指向ha的最後一個結點
hb->next->prior=ha->prior;
hb->prior->next=ha;
ha->prior=hb->prior;
}
free(hb); //釋放hb頭結點
}
int main()
{
CDLinkList *HA, *HB;
ElemType ha[]= {0, 1, 2, 3, 4, 5, 6, 7 ,8, 9};
InitList(HA);
CreateListF(HA, ha, 10);
ElemType hb[]= {100, 200, 300, 400, 500};
InitList(HB);
CreateListF(HB, hb, 5);
printf("HA: ");
DispList(HA);
printf("HB: ");
DispList(HB);
Insert(HA, HB, 0); //將0改爲其他值,多次運行程序完成測試
printf("new HA: ");
DispList(HA);
DestroyList(HA);
return 0;
}
運行結果:
心得體會:
要注意總結雙鏈表與單鏈表的相同之處,便與學習。