鍊錶的實現 LinkedList (Java實現)

2021-09-12 15:58:36 字數 2165 閱讀 3773

public

class

linkedlist

public

node

(e e)

public

node()

public string tostring()

}// 虛擬的頭結點

private node dummyhead;

private

int size;

public

linkedlist()

// 獲取鍊錶的元素個數

public

intgetsize()

// 判斷鍊錶是否為空

public

boolean

isempty()

// 插入元素

public

void

add(

int index, e e)

node pre = dummyhead;

for(

int i =

0, i < index, i++

) node node =

newnode

(e);

node.next = pre.next;

pre.next = node;

size ++;}

// 在鍊錶的頭部新增新的元素

public

void

addfirst

(e e)

// 在鍊錶的尾部新增節點

public

void

addlast

(e e)

// 獲得鍊錶的index的元素

public e get

(int index)

node cur = dummynode.next;if(

int i =

0; i < index; i++

)return cur.next;

}//獲得鍊錶的第乙個元素

public e getfirst()

// 獲得最後乙個元素

public e getlast()

// 修改鍊錶index的元素

public

void

set(

int index)

node cur = dummyhead.next;

for(

int i =

0; i < index; i++

) cur.e = e;

}// 查詢鍊錶中是否存在e

public

boolean

contains

(e e)

cur = cur.next;

}return

false;}

// 鍊錶的刪除

public e delete

(int index)

node pre = dummyhead;

for(

int i =

0; i < index; i++

) node ret = pre.next;

pre.next = ret.next;

ret.next = null;

size --

;return ret.e;

}// 刪除第乙個元素

public e removefirst()

// 刪除最後乙個元素

public e removelast()

@override

public string tostring()

sb.("null");

return sb.

tostring()

;}}

public

class

main

linkedlist.

add(2,

666)

; system.out.

println

(linkedlist)

; linkedlist.

delete(2

);system.out.

println

(linkedlist);}

}

LinkedList 鍊錶

線性表是一種簡單的資料結構,其主要特點是元素之間存在 一對一 的關係,除去第乙個元素,每個元素都存在唯一乙個 前驅節點 除去最後乙個元素都存在唯一乙個 後繼節點 簡單的線性表有 陣列 單鏈表 雙向鍊錶 靜態鍊錶等。順序表 陣列 優缺點 陣列不僅邏輯上,物理上位置也相鄰,可隨機訪問,但刪除或插入元素時...

LinkedList 鍊錶

最近複習到鍊錶 linkedlist 一般來說共有大概有兩種實現方式 1.陣列實現 和 2.鏈式實現。我僅使用了直接鏈式實現,如下。其他的實現方式,大家不妨自己嘗試下吧。author ace yom peizhen zhang date 2015 8 17 description 鍊錶實現 ifnd...

鍊錶 LinkedList

原文中singlelinklist的remove方法有問題,因為是 node current firstnode.getnext 所以導致鍊錶的第乙個節點刪不掉。修改如下 public class singlelinklist 刪除某個節點 param element return 刪除成功返回tr...