靜態鍊錶結構
首先我們先來看看靜態鍊錶的結構定義
typedef structcomponent,staticlinklist[maxsize]
;
status initlist(staticlinklist l)
l[maxsize-2].cur = 0; //備用鍊錶的表尾
l[maxsize-1].cur = 0; //資料鏈表表頭
return ok;
}
初始化為空的靜態鍊錶如下圖一所示
圖一 空的靜態鍊錶
在備用鍊錶中插入資料
接下來才是重點!!!實際上靜態鍊錶分為兩個鍊錶:備用鍊錶和資料鏈表(兩表的表頭位置如上圖一所示)。備用鍊錶將未使用空間串聯起來,資料鏈表才是真正存放資料的地方,那麼具體是怎樣儲存資料的呢?接下來我們在資料鏈表中插入數字1,看以下向資料鏈表中插入資料的**:
status insertlist(staticlinklist l,int i,elemtype e)
printf(
"備用鍊錶為空!\n");
return error; //備用鍊錶為空 }
/**/
int malloc_l(staticlinklist l)
return i;
}
呼叫如下插入函式,其效果如下圖二。
圖二 向備用鍊錶新增乙個元素
圖二中用紅色字型標註的顯然是資料鏈表了,剩下的黑體字標註的是備用鍊錶,每當要插入乙個資料時,備用鍊錶中便有一塊空間轉化成資料鏈表的空間,其轉換細節分為以下四個步驟:
記錄備用煉表頭l[0]游標,更改l[0]游標為2,使其指向l[2],此時備用鍊錶操作完成
給l[1]的資料元素賦值,l[1]將加入資料鏈表中
遍歷資料鏈表l[4]到要插入位置(第i位置)的前乙個資料元素(第i-1位置),將位於i-1位置的元素游標賦值給位於i位置的元素游標
將插入元素的位置i賦值給位於i-1位置的元素游標,資料鏈表的插入操作完成
通過以上步驟的分析相信大家都已經熟悉了靜態鍊錶的插入操作,那麼接下來再執行以下函式,你們能畫出靜態鍊錶的資料結構圖嗎?
//綜合**
#include
"staticlist.h"
intmain()
#include
"staticlist.h"
intinitstaticlist
(staticlist l)
//通常陣列第乙個下標和最後乙個下標的資料域不用,這裡先把它初始化為0
l[max - max]
.data =0;
l[max -1]
.data =0;
l[max -1]
.next =0;
return1;
}int
lengthstatic
(staticlist l)
return j;
}void
printstaticlist
(staticlist l)
}void
printcursor
(staticlist l)
return;}
intmalloc
(staticlist l)
return cursor;
}void
insertstaticlist
(staticlist l,
int i,
int value)
j =malloc
(l);
if(j)
l[j]
.next= l[k]
.next;
l[k]
.next=j;
}return;}
void
free_ssl
(staticlist l,
int k)
//將下標為k的空閒節點**為備用鍊錶
intdelstaticlist
(staticlist l,
int i)
for(j =
1; j <= i -
1; j++
) j = l[k]
.next;
//這兩句的意思是如果有元素被刪除了,就更新最後乙個陣列元素的游標
l[k]
.next = l[j]
.next;
free_ssl
(l, j)
;//如果有新的元素插進來,就優先考慮以前刪除的空位置
return1;
}
#ifndef _staticlist_h
#define _staticlist_h
#include
#include
#include
#define max 10
typedef struct node
staticlist[max]
;extern int initstaticlist(staticlist l)
;extern void printstaticlist(staticlist l)
;extern void printcursor(staticlist l)
;extern int lengthstatic(staticlist l)
;extern int malloc(staticlist l)
;extern void insertstaticlist(staticlist l, int i, int value)
;extern void free_ssl(staticlist l, int k)
;extern int delstaticlist(staticlist l, int i)
;#endif
參考: 鍊錶相關操作
include include using namespace std 鍊錶結構體 struct listnode 是否為空 bool isempty listnode list position是否是最後乙個 bool islast listnode position,listnode list ...
鍊錶相關操作
class listnode 1.鍊錶反轉,遍歷原鍊錶,採用頭插法將數值插入新鍊錶 public listnode reverse listnode p return cur 2.兩個鍊錶相加,如 1 2 3加4 5 6等於5 7 9。思路 短的鍊錶高位用0補。public class soluti...
鍊錶相關操作
關於鍊錶的頭插法 尾插法 刪除節點 插入節點。include include typedef struct listlist,linklist linklist creat onhead linklist head,int x linklist creat ontail linklist head,...