第四周实践项目6 循环双链表应用
生活随笔
收集整理的這篇文章主要介紹了
第四周实践项目6 循环双链表应用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
/*
*Copyright (c) 2017,煙臺大學計算機與控制工程學院
*All rights reserved.
*文件名稱:項目6-設非空線性表ha和hb都用帶頭節點的循環雙鏈表表示。設計一個算法Insert(ha,hb,i)。其功能是:i=0時,將線性表hb插入到線性表ha的最前面;當i>0時,將線性表hb插入到線性表ha中第i個節點的后面;當i大于等于線性表ha的長度時,將線性表hb插入到線性表ha的最后面。
*作 者:邵雪源
*完成日期:2017年12月13日
*版 本 號:v1.0
*/
#include <stdio.h>
#include <malloc.h>
typedef int ElemType;
typedef struct DNode //定義雙鏈表結點類型
{ElemType data;struct DNode *prior; //指向前驅結點struct DNode *next; //指向后繼結點
} CDLinkList;
void CreateListF(CDLinkList *&L,ElemType a[],int n) //頭插法建立循環雙鏈表
{CDLinkList *s;int i;L=(CDLinkList *)malloc(sizeof(CDLinkList)); //創建頭結點L->next=NULL;for (i=0; i<n; i++){s=(CDLinkList *)malloc(sizeof(CDLinkList));//創建新結點s->data=a[i];s->next=L->next; //將*s插在原開始結點之前,頭結點之后if (L->next!=NULL) L->next->prior=s;L->next=s;s->prior=L;}s=L->next;while (s->next!=NULL) //查找尾結點,由s指向它s=s->next;s->next=L; //尾結點next域指向頭結點L->prior=s; //頭結點的prior域指向尾結點}
void InitList(CDLinkList *&L) //初始化循環雙鏈表
{L=(CDLinkList *)malloc(sizeof(CDLinkList)); //創建頭結點L->prior=L->next=L;
}
void DestroyList(CDLinkList *&L) //銷毀
{CDLinkList *p=L,*q=p->next;while (q!=L){free(p);p=q;q=p->next;}free(p);
}
void DispList(CDLinkList *L) //輸出鏈表
{CDLinkList *p=L->next;while (p!=L){printf("%d ",p->data);p=p->next;}printf("\n");
}
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;
}
總結
以上是生活随笔為你收集整理的第四周实践项目6 循环双链表应用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 第四周实践项目5 猴子选大王(循环链表)
- 下一篇: 第四周实践项目7 多项式求和