[cpp]view plain
copy
/** linkedlist
* linc
* 2013.2.26
*/#include
#include
#include
#define ok 1
#define error -1
#define ture 1
#define false 0
struct
node
; typedef
struct
node *head;
typedef
struct
node *linkedlist;
//create the linked list,head insert
void
createlist(linkedlist *list,
intsize,head *head)
//head node
tmplist = (linkedlist)malloc(sizeof
(struct
node));
tmplist->data = size;
tmplist->next = (*list)->next;
(*list)->next =tmplist;
/*while((*list) != null)
*/}
//get element of list
intgetelement(linkedlist list,
intindex,
int*element)
intcount = 0;
while
(tmplist && count < index+1)
//+1 for head node
if(!tmplist)
return
error;
*element = tmplist->data;
return
ok;
} //clear list
intclearlist(linkedlist *list)
(*list)->next = null;
return
ok;
} //insert
//after index
intinsert(linkedlist *list,
intindex,
intelement)
intcount = 0;
while
(tmplist && count < index+1)
if(!tmplist)
return
error;
linkedlist node = (linkedlist)malloc(sizeof
(struct
node));
node->data = element;
node->next = tmplist->next;
tmplist->next = node;
return
ok;
} //delete
intdelete
(linkedlist *list,
intindex)
intcount = 0;
while
(tmplist && count < index+1)
if(!tmplist)
return
error;
linkedlist node = tmplist->next;
tmplist->next = node->next;
free(node);
return
ok;
} int
main()
鏈式儲存結構的優點在於它在找到目標元素後,刪除或者插入都十分方便,只需將指標挪動一次就好;缺點就是不能像順序儲存結構那樣迅速的找到目標元素,只能笨笨的乙個乙個元素的遍歷下去。
線性表之單鏈表
零個或多個資料元素的有限序列,線性表中的元素是一對一的關係,除了第乙個元素和最後乙個元素外,其他元素都是首尾相接的。線性表有兩種儲存方式,一種是順序儲存結構,另一種是鏈式儲存結構。指用一段位址連續的儲存單元依次儲存線性表的資料元素。優點 無需為表示元素間的邏輯關係而增加額外的儲存空間 隨機查詢元素,...
線性表之單鏈表
template typenamet structnode 頭結點 如果鍊錶有頭節點,則鏈式結構中的第乙個節點稱為頭結點 其資料域可以儲存一些附加資訊,如鍊表長度 其指標域指向鍊錶中的第乙個節點。template class linklist linklist t a int n linklist ...
線性表之單鏈表
一 帶頭結點的構建和插入 include includestruct lnodelnode,linklist bool initlist linklist l l next null return true bool listinsert linklist l,int i,int e lnode p...