1.概述:
鏈式描述中,線性表的元素存在記憶體中的位置是隨機的。
基於陣列的描述中,元素的位址是由數學公式決定的,而在鏈式描述中,元素的位址是隨機分布的.
2.單向鍊錶:
2.1 描述
資料物件的例項的每個元素都用乙個單元或節點來描述。
每個節點都明確包含另乙個相關節點的位置資訊,稱為鏈或指標。
一般來說,為找到索引為theindex的元素,需要從firstnode開始,跟蹤theindex個指標才能找到.
2.2結構chainnode
為用鍊錶描述線性表,定義乙個結構chainnode和乙個類chain.
結構chainnode**如下:
類chain的定義**如下://鍊錶節點的結構定義
templatet>
struct chainnode
chainnode(const t & element)
chainnode(const t & element,chainnode* next)
};
鍊錶的構造和複製建構函式、析構函式**如下:// 鍊錶節點的結構定義
templateclass chain:public linearlist
int size()const
t & get(int theindex)const;
int indexof(const t &theelement);
void erase(int theindex,const t & theelement);
void output(ostream & out)const;
protected:
void
checkindex(int theindex)const;
//資料成員
chainnode* firstnode;//指向鍊錶第乙個節點的指標
int listsize;//線性表的元素個數
};
時間複雜度://建構函式
templatet>
chain::chain(int initialcapacity)
firstnode=null;
listsize=0;
}//複製建構函式
templatet>
chain::chain(const chain & thelist)
//鍊錶節點為非空
chainnode* sourcenode=thelist.firstnode;//要複製的thelist的節點
firstnode=new chainnode (sourcenode->element);//複製鍊錶thelist的首元素
sourcenode=sourcenode->next;
chainnode* targetnode=firstnode;//當前鍊錶*this的最後乙個節點
while (sourcenode!=null)
}//析構函式
templatet>
chain::~chain()
}
建構函式為o(1),複製建構函式要複製鍊錶thelist的每乙個節點,因此時間複雜度是o(max
//返回元素theelement首次出現時的索引
template
int chain::indexof(const t & theelement)const
//確定是否找到所需要的元素
if (currentnode==null)
else
return index;
}//刪除索引為theindex的元素
template
void chain::erase(int theindex)
else
}listsize--;
delete deletenode;
}//插入元素theelement 並使其索引為theindex
template
void chain::insert(int theindex,const t & theelement)
if (theindex==0)
else
p->next=new chainnode(theelement,p->next);
//覺得此處有問題,插入之後為什麼沒有和後面的節點連線起來
}listsize++;
}//方法output、輸出鍊錶
template
void chain::output(ostream & out)const
}//過載<<
template
ostream & operator<<(ostream & out,const chain& x)
時間複雜度:
get()複雜度在鍊錶中o(theindex),在陣列描述的線性表中o(1).
indexof():在鍊錶描述的線性表中,唯一的方法是用當前節點的指標確定下乙個相鄰節點的位置,複雜度為o(listsize).
erase():複雜度為o(theindex),而arraylist::erase 的時間複雜度是o(listsize-theindex).因此在接近表頭的位置實施刪除操作時,鏈式描述的線性表比陣列描述的線性表有更好的時間效能.
insert():為在鍊錶中索引為theindex的位置上插入乙個新元素,需要首先找到索引為theindex-1的元素節點,然後在該節點之後插入新元素節點,複雜度為o(theindex).
output():複雜度為o(listsize).
3.迴圈鍊錶:
在鍊錶的前面增加乙個節點,稱為頭節點,只要將單向鍊錶的尾節點與頭節點鏈結起來,單向鍊錶就稱為迴圈鍊錶.下面是帶有頭節點的迴圈鍊錶的建構函式**和indexof**.
4.雙向鍊錶:搜尋帶有頭節點的迴圈鍊錶
template
circularlistwithheader::circularlistheader()
template
int circularlistwithheader::indexof(const t & theelement) const
//確定是否找到元素theelement
if (currentnode==headernode)
return -1;
else
return index;
}
暫時留著,後序補充上來.
鏈式線性表
2013 03 23 00 14 39 上學期的時候就大致看了資料結構與演算法分析的了,但感覺收穫比較少,總結原因是程式設計實踐少了,所以今年趁著老師上課,就多進行一些 的實踐,也準備拿一些acm的題目來練練。中午的時候就將鏈式表的 打了一遍,現在貼上來分享。為了節省時間,我的注釋也相對較少,有不懂...
線性表續篇 線性表的鏈式表示
public class 04linearlist02 初始化指標域和資料域 private node t obj,node n 得到當前節點的資料域 public t getdata 得到當前節點的指標域 public node getnext 鍊錶的長度 private int length 鍊...
鏈式線性表和順序線性表
在這裡插入 片 線性表的儲存結構 typedef struct seqlist typedef struct seqlist 順序表基本操作 初始化順序表在這裡插入 片 intseqlist init seqlist list,int size 插入資料元素在這裡插入 片 intseqlist in...