对于线性链表,也可用一维数组来进行描述。这种描述方法便于在没有指针类型的高级程序设计语言中使用链表结构。
用数组描述的链表,即称为静态链表。
在C语言中,静态链表的表现形式即为结构体数组,结构体变量包括数据域数据和游标坏蛋。
数据域:用于存储数据元素的值
游标:即数组下标,表示直接后继元素所在数组中的位置
公开课StaticLinkedListNode{ 公共T数据;//数据 公共int光标;//游标 … } >之前 注:通常静态链表会将第一个数据元素放到数组下标为1(即[1])的位置中。
静态链表中,除了数据本身通过游标组成链表外,还需要有一条连接各个空闲位置的链表,称为备用链表。
作用:回收数组中未使用或者之前使用过(现在不用)的存储空间,留待后期使用。即静态链表使用数组申请的物理空间中,存在两个链表,一条连接数据,另一条连接数组中为使用的空间。
<强>注:通常备用链表的表头位于数组下标为0([0])的位置,而数据链表的表头位于数组下标为1([1])的位置。强>
静态链表中设置备用链表的好处是,可以清楚地知道数组中是否有空闲位置,以便数据链表添加新数据时使用。比如,若静态链表中数组下标为0的位置上存有数据,则证明数组已满。
公开课StaticLinkedListNode{ 公共T数据; 私人int光标; 公共StaticLinkedListNode (T数据,int光标){ 这一点。光标=光标; } 公共T getData () { 返回数据; } 公共空间setData (T数据){ 这一点。数据=https://www.yisu.com/zixun/data; } 公共int getCursor () { 返回指针; } 公共空间setCursor (int光标){ 这一点。光标=光标; } } >之前 公开课StaticLinkedList{ StaticLinkedListNode[]节点; 私有静态最终int MAX_SIZE=100; 私人int长度; 公共StaticLinkedList () { 节点=new StaticLinkedListNode [MAX_SIZE]; for (int i=0;我& lt;MAX_SIZE;我+ +){ 节点[我]=new StaticLinkedListNode (null, i + 1); } 节点(MAX_SIZE - 1) .setCursor (0); 这一点。长度=0; }//链表实际长度 公共int长度(){ 返回长度; }//判断使用数组是否为空 公共布尔isEmpty () { 返回长度==0; }//判断备用链表是否为空 公共布尔isFull () { 返回长度==MAX_SIZE; }//插入一个节点 公共布尔遭受(T数据,int指数){ 如果(isFull() | |指数比;MAX_SIZE | |指数& lt;1 | | data=https://www.yisu.com/zixun/=零) 返回错误; 如果(指数==0){ 插入(数据); 返回true; } 如果(指数>长度()){ 指数=长度(); }//获取第一个使用节点的下标 int [MAX_SIZE - 1] .getCursor firstUse=节点();//获取备用数组第一个节点的下标 int firstNull[0]=节点.getCursor (); for (int i=1;我<指数;我+ +){ firstUse=节点[firstUse] .getCursor (); }//获取目标节点的后续节点 int [firstUse] .getCursor nextUse=节点(); int [firstNull] .getCursor nextNull=节点(); 节点[0].setCursor (nextNull); 节点[firstUse] .setCursor (firstNull); 节点[firstNull] .setCursor (nextUse); 节点[firstNull] .setData(数据); 长度+ +; 返回true; } 公共空间插入数据(T) { int [MAX_SIZE - 1] .getCursor t=节点(); int firstNull[0]=节点.getCursor (); 节点(MAX_SIZE - 1) .setCursor (firstNull); 节点[0].setCursor(节点[firstNull] .getCursor ()); 节点[firstNull] .setCursor (t); 节点[firstNull] .setData(数据); 长度+ +; } 公共空间print () { int第一节点=[MAX_SIZE - 1] .getCursor (); System.out.println(“链表:”); for (int i=第一;我!=0;{ [我].getData System.out.print(节点()+ " "); i=[我].getCursor节点(); } }//删除指定节点 公共逻辑删除(T数据){ 如果(isEmpty ()) { 返回错误; } int temp=MAX_SIZE - 1; 而(临时!=0){ 如果节点(节点(临时).getCursor ()] .getData()==数据){ int(临时).getCursor p=节点(); 节点(临时).setCursor(节点[p] .getCursor ()); 节点[p] .setCursor(节点[0].getCursor ()); 节点[0].setCursor (p); 节点[p] .setData(空); 长度,; 返回true; } temp=节点(临时).getCursor (); } 返回错误; }//删除所有节点 公共布尔deleteAll () { 如果(isEmpty ()) { 返回true; } for (int i=0;我& lt;MAX_SIZE - 1;我+ +){ 节点[我]。setCursor (i + 1); 节点[我].setData(空); } 节点(MAX_SIZE - 1) .setCursor (0); 节点(MAX_SIZE - 1) .setData(空); 长度=0; 返回true; } 公共空间printAll () { System.out.println(“链表:”); for (int i=0;我& lt;MAX_SIZE;我+ +){ system . out。打印(“[”+我+ " " +节点[我].getData() + " " +节点[我].getCursor () + ") "); 如果(我% 5==0,,我!=0){ System.out.println (); } } } 公共静态void main (String [] args) { StaticLinkedList 用Java实现一个静态链表的方法步骤