線性表 單鏈表

2021-09-27 12:18:10 字數 1578 閱讀 2164

單鏈表結構與順序儲存結構對比:

一、儲存分配方式

1、順序儲存結構用一段連續的儲存單元依次儲存線性表的資料元素

2、單鏈表採用鏈式儲存結構,用一組任意的儲存單元存放線性表的元素

二、時間效能

1、查詢:順序儲存結構o(1);單鏈表o(n)

2、插入和刪除:順序儲存結構o(n);單鏈表找到位置後插入刪除時間o(1)

三、空間效能

1、順序儲存結構需要預先分配儲存空間,分大了浪費,分小了容易發生溢位

2、單鏈表不需要分配儲存空間,只要有就可以分配,元素個數也不受限制

#include#include#includeusing namespace std;

#define true 1

#define false 0

typedef int status;

typedef int elemtype;

typedef struct node

node;

typedef struct node *linklist; //定義linklist

//獲取到鍊錶中第i個節點的元素並返回給e

status getelem(linklist l,int i,elemtype *e)

if(p==null || count>i) //如果i=0或者找到尾指標都沒找到,返回0

return false;

*e=p->data;

return true;

}//向鍊錶中第i的位置插入元素e

status listinsert(linklist *l,int i,elemtype e)

if(p==null || count>i)

return false;

s=(linklist)malloc(sizeof(node));

s->data=e;

s->next=p->next;

p->next=s;

return true;

}//刪除鍊錶中第i個節點,並將該節點的元素返回給e

status listdelete(linklist *l,int i,elemtype *e)

if(p->next==null || count>i)

return false;

q=p->next;

p->next=q->next;

*e=q->data;

free(q);

return true;

}//頭插法建立n個元素帶表頭節點的單鏈表l

void createlisthead(linklist *l,int n)

}//尾插法建立n個元素帶表頭節點的單鏈表l

void createlisttail(linklist *l,int n)

}//清空整個單鏈表,置l為空表,表頭指向null

status clearlist(linklist *l)

(*l)->next=null;

return true;

}int main()

return 0;

}

線性表 單鏈表

define crt secure no deprecate define crt secure cpp overload standard names 1 includeusing namespace std typedef struct node node node headpointer 頭指...

線性表 單鏈表

template struct node template class linklist 無參建構函式,建立只有頭結點的空鍊錶 linklist t a int n 有參建構函式,建立有n個元素的單鏈表 linklist 析構函式 int length 求單鏈表的長度 t get int i 按位查...

線性表 單鏈表

1 單鏈表的結點定義 typedef struct node slnode 2 初始化listinitiate slnode head void listinitiate slnode head 初始化 3 求當前資料元素個數listlength slnode head int listlength...