資料結構 雙向鍊錶的實現

2021-10-03 11:18:25 字數 1968 閱讀 7443

帶頭結點,不帶頭結點的類似

#include #include #define elemtype int

typedef struct dnodednode, *dlinklist;

// 雙向鍊錶的初始化

bool initdlinklist(dlinklist &l)

// 雙鏈表 查詢指定idx位置的結點

dnode* getnode(dlinklist &l, int idx)

dnode *p = l;

int j = 0;

while(p->next != null && j < idx)

return p;

}// 雙鏈表在指定p結點之後插入s結點

bool insertnextnode(dnode *p, dnode *s)

s->next = p->next;

if(p->next != null)

s->prior = p;

p->next = s;

return true;

}// 在指定位置插入結點p

bool listinsert(dlinklist &l, int idx, dnode *p)

dnode *s = getnode(l, idx-1); // 獲取第idx-1個結點

if(s == null)

// printf("here\n");

return insertnextnode(s, p); // 在第idx-1之後插入p結點

}// 雙鏈表 刪除指定p結點的後繼結點

bool deletenextnode(dnode *p)

dnode *s = p->next; // 待刪除結點

if(s->next != null)

p->next = s->next;

free(s);

return true;

}// 銷毀雙鏈表

bool destroylist(dlinklist &l)

free(l);

return true;

}bool isempty(dlinklist l)

// 頭插法建立雙鏈表

dlinklist listheadinsert(dlinklist &l)

l = (dnode *)malloc(sizeof(dnode));

l->next = l->prior = null;

elemtype e;

while(scanf("%d", &e) != eof)

newnode->prior = l;

l->next = newnode;

} return l;

}// 尾插法建立雙鏈表

dlinklist listtailinsert(dlinklist &l)

// l = (dnode *)malloc(sizeof(dnode));

// l->prior = l->next = null;

elemtype e;

dnode *tail = l;

while(tail->next != null)

while(scanf("%d", &e) != eof)

return l;

}int main()

dnode *node = (dnode *)malloc(sizeof(dnode));

node->data = 10;

insertnextnode(l, node);

deletenextnode(l);

// listheadinsert(l);

listtailinsert(l);

dnode *p = l->next;

int i = 1;

while(p != null)

return 0;

}

資料結構 鍊錶 雙向鍊錶

注意typedef的定義結構,以及dinklist的資料型別 typedef struct dnode dnode,dinklist 注意插入第乙個結點時,prior指標的空指向問題 if l next null 若l後繼結點為空 則省略該步驟 l next prior p 基本 頭插法建立雙向鍊錶...

資料結構 雙向鍊錶

前幾天寫了乙個單向鍊錶,今天參考自己單向鍊錶改寫了乙個雙向非迴圈鍊錶,下面只討論雙向非迴圈鍊錶。雙向非迴圈鍊錶有如下特點 一 雙向鍊錶每個結點都有乙個前驅指標和後驅指標 當然頭結點和尾結點除外 二 雙向鍊錶中的任意乙個結點開始,都可以很方便地訪問它的前驅結點和後繼結點。三 頭結點只有後驅指標沒有前驅...

資料結構 雙向鍊錶

單鏈表的單向性 只能從頭結點開始高效訪問鍊錶中的資料元素。單鏈表還存在另乙個缺陷 逆序訪問時候的效率極低。如下 linklistlist for int i 0 i 5 i for int i list.length 1 i 0 i 根據大o推算法可以得出乙個for迴圈的時間複雜度為o n get ...