資料結構學習心得——雙鏈表和迴圈連結串列
阿新 • • 發佈:2019-02-04
雙鏈表
若要尋查結點的前驅,則需要從表頭指標出發。為了克服單鏈表這種單向性的缺點,可以利用雙鏈表。顧名思義,在雙鏈表的結點中有兩個指標域,其一指向直接後繼,另一指向直接前驅。
迴圈連結串列
迴圈連結串列是另一種形式的鏈式儲存結構。它的特點是表中最後一個結點的指標域指向頭結點,整個連結串列形成一個環。由此,從表中任一結點出發均可找到表中其他結點。
程式碼實現
#include <iostream>
using namespace std;
typedef struct LNode
{
int data;
struct LNode *next;
}LNode;
typedef struct DLNode
{
int data;
struct DLNode *prior;
struct DLNode *next;
}DLNode;
//雙鏈表的建立同樣有尾插法和頭插法兩種建立方法
//這裡使用的是尾插法
void createDlist(DLNode *&L,int a[],int n)
{
DLNode *q;
DLNode *p = L;
int i;
for(i=0;i<n;i++)
{
q = new DLNode;
q->data = a[i];
p->next = q;
q->prior = p;
p = q;
}
p->next = NULL;
}
//用尾插法建立迴圈連結串列
void createList(LNode *&L,int a[],int n)
{
LNode *q;
LNode *p = L;
int i;
for(i=0;i<n;i++)
{
q = new LNode;
q->data = a[i];
p->next = q;
p = q;
}
p->next = L;
}
//輸出雙鏈表中所有元素的值
void printDList(DLNode *head)
{
DLNode *p = head->next;
while (p!=NULL)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
//輸出迴圈連結串列中的所有元素
void printList(LNode *head,int n)
{
int i;
LNode *p = head->next;
for(i=0;i<n;i++)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
int main()
{
DLNode *Dhead = new DLNode;
Dhead->next = NULL;
Dhead->prior = NULL;
LNode *head = new LNode;
head->next = NULL;
int a[6]={2,3,4,7,9,8};
createDlist(Dhead,a,6);
createList(head,a,6);
printDList(Dhead);
printList(head,6);
return 0;
}
程式碼執行截圖: