定義乙個單鏈表

2021-10-24 23:24:28 字數 2387 閱讀 7000

鍊錶是一種物理儲存結構上非連續、非順序的儲存結構,資料元素的邏輯順序是通過鍊錶中的指標鏈結次序實現的 。

鍊錶是由乙個乙個的節點相連線的,每乙個節點都是乙個物件,都有兩個屬性(data,next)。

根據鍊錶的結構可以分為:

1.帶頭、不帶頭

2.單向、雙向

3.迴圈、非迴圈

這些組合起來就有8種結構;

編寫乙個具有簡單功能的不帶頭結點的單向非迴圈鍊錶。

class

node

}public

class

mylinkedlist

/**單鏈表的插入的時候,要先綁後面*/

node.next =

this

.head;

//將head的引用傳給node的next

this

.head = node;

//讓head指向node的引用

//注意不能寫成this.head=this.node;因為note是具體方法中定義的區域性變數,而this只能訪問屬性,方法,構造方法等。

}//列印單鏈表

public

void

display()

system.out.

println()

;}//尾插法(插入的資料會順序輸出)

public

void

addlast

(int data)

node cur =

this

.head;

while

(cur.next != null)

cur.next = node;

}//得到單鏈表的長度

public

intsize()

return count;

}//查詢關鍵字key是否包含在單鏈表中

public

boolean

contains

(int key)

cur = cur.next;

}return

false;}

//按索引插入

//1.任意位置插入,第乙個資料節點的下標為0

//2.要往index位置插入,則需要cur先走到index-1的位置,然後node.next=cur.next;cur.next=node;

public

void

addindex

(int index,

int data)

if(index ==

this

.size()

)//先要找到index-1位置的節點的位址

node cur =

searchindex

(index)

;//進行插入

node.next = cur.next;

cur.next = node;

}private node searchindex

(int index)

node cur =

this

.head;

while

(index -1!=

0)return cur;

}private node searchprev

(int key)

else

}return null;

}//刪除第一次出現關鍵字key的節點

public

void

remove

(int key)if(

this

.head.data == key)

node prev =

searchprev

(key)

;//找到要刪除節點的前驅

if(prev == null)

else

}//刪除所有值為key的節點

public

void

removeallkey

(int key)

else}if

(this

.head.data == key)

}//釋放記憶體

public

void

clear()

鍊錶的優點:1.任意位置插入刪除時間複雜度為o(1)。

2.沒有增容問題,插入乙個開闢乙個空間。

缺點:以節點為儲存單位,不支援隨機訪問。

反轉乙個單鏈表

思路二 反轉乙個鍊錶 示例 結構體定義 先對原鍊錶做頭刪操作,再對新鍊錶做頭插定義乙個新head頭指標,標記為newhead,將它初始為null,並非指向null,最後我們選擇返回這個newhead指標作為新鍊錶的頭指標。定義乙個結點node作為 臨時中轉站 初始化與否並無大影響。進行迴圈遍歷鍊錶各...

反轉乙個單鏈表

反轉乙個單鏈表。示例 輸入 1 2 3 4 5 null 輸出 5 4 3 2 1 null高階 你可以迭代或遞迴地反轉鍊錶。你能否用兩種方法解決這道題?解題心路 迭代好說,遞迴 第一思路將後面的全部翻轉好,再將最後乙個元素的next指向當前。返回最後乙個元素的指標,那就有 當前節點指標 head ...

將乙個單鏈表逆序

struct list node int data list node next void reserve list node phead 測試程式 list lt lt.phead new list node 0,0 lt.phead next new list node 1,0 lt.phead...