直接上**,親測有用。
#ifndef __dlink_h__#define __dlink_h__
/*[phead] -> [index0] -> [index1] -> [index2] -> ...... [phead]
[phead] <- [index0] <- [index1] <- [index2] <- ...... [phead]
phead 不儲存資料。 index是從0開始的。count = index + 1;
*/template
struct
node
node(t a, node *p1, node *p2)
node *next;
node *prev;
t data;
};template
class
dlink
;template
dlink
::dlink()
template
dlink
::~dlink()
template
node
*dlink::get_node(int
index)
#if 0node
*pnode = m_phead->next;
int i = 0
;
while(i pnode = pnode->next;
i++;
}#else
//正向查詢
if(index <= m_ncount/2
)
pnode = pnode->next;
i++;}}
else
//反向查詢
pnode = pnode->prev;
i--;}}
#endif
return
null;
}template
int dlink::create_dlink()
template
int dlink::destroy_dlink()
node
*pnode = m_phead->next;
node
*tmp;
while(pnode !=m_phead)
delete
m_phead;
m_phead =null;
m_ncount = 0
;
return0;
}template
int dlink::getcount()
//index 表示要插入後的位置,所以這裡可以等於m_ncount。表示在最後乙個
template
int dlink::insert_dlink(int
index, t tdata)
if(index < 0 || index >m_ncount)
if(index == 0
)
if(index ==m_ncount)
node
*pindex =get_node(index);
node
*pnode = new node(tdata, pindex->prev, pindex);
pindex->prev->next =pnode;
#if 0 // 20180223 update. 突然發現這裡寫錯了
pindex->next->prev =pnode;
#endif
pindex->prev = pnode; // 改為這樣
m_ncount++;
return0;
}template
int dlink::insert_dlink_first(t tdata)
node
*pnode = new node(tdata, m_phead, m_phead->next);
if(!pnode)
m_phead->next->prev =pnode;
m_phead->next =pnode;
m_ncount++;
return0;
}template
int dlink::insert_dlink_last(t tdata)
node
*pnode = new node(tdata, m_phead->prev, m_phead);
if(!pnode)
m_phead->prev->next =pnode;
m_phead->prev =pnode;
m_ncount++;
return0;
}template
t dlink
::get_dlink(int
index)
return pnode->data;
}template
t dlink
::get_dlink_first()
template
t dlink
::get_dlink_last()
//index 是從0開始編號的。這裡的範圍是 0 -- m_ncount-1
template
int dlink::delete_dlink(int
index)
node
*pnode =get_node(index);
if(pnode)
return -1;}
template
int dlink::delete_dlink_first()
template
int dlink::delete_dlink_last()
#endif
//__dlink_h__
測試:
#include#include"dlink.h
"using
namespace
std;
void
fun1()
;
for(int i = 0; i < 5; i++)
pdlink->insert_dlink(5, 4444
);//
pdlink->delete_dlink(1);
//pdlink->destroy_dlink();
int count = pdlink->getcount();
cout
<< "
fun1() count:
"<< count
cout
<< "
fun1() ---
"<}int
main()
關於為何c++的模板類宣告和實現要放在一起可以參考:
乙個雙向鍊錶的實現
本來是想改改算了,最後變成全部重寫。既然都是自己寫的,也算是原創吧!struct node node intval,node nextnode,node priornode data val next nextnode prior priornode node headnode new node n...
自己實現乙個雙向鍊錶
雙向鍊錶和單向鍊錶不同的是雙向鍊錶中不僅有next指向,還有pre這個指向,分別指向了該節點的前乙個節點和後乙個節點,這樣比單向鍊錶操作起來更方便.class twonode public class mylinkedlist 0.求鍊錶長度 public intlength 1.頭插 public...
C 實現簡單的雙向鍊錶
vs2013下編譯執行,實現了雙向鍊錶類list 的 建構函式,拷貝構造 析構函式 賦值運算子過載 清空 頭插 頭刪 尾插 尾刪 插入 刪除 逆序和刪除鍊錶中重複的資料值函式等。直接貼 dulist.h 類宣告 定義 成員函式定義。pragma once 雙向鍊錶 include includeus...