資料結構與演算法學習(一) 單鏈表相關演算法

2021-10-18 19:23:28 字數 4290 閱讀 2996

建立node節點類的**如下

public

class

node

@override

public string tostring()

';}}

建立鍊錶類並編寫鍊錶類的新增節點和遍歷方法

public

class

linkedlist

//由於單鏈表的頭節點不可移動,所以我們使用乙個臨時指標來輔助我們新增節點。

node temp = head;

while

(true

) temp = temp.next;

}//退出迴圈時,temp節點指向鍊錶最後乙個節點,此時將傳入節點掛在temp之後即可

temp.next = node;

}/***

* 遍歷鍊錶的方法

*/public

void

list()

node temp = head;

while

(true

) system.out.

println

(temp)

; temp = temp.next;}}

}

這裡使用遞迴來完成單鏈表的反轉,這個演算法的思路大體如下

實現**如下

/***

* * @param head

* @return

*/public

static node reverse

(node head)

//如果鍊錶長度大於等於2,進行遞迴

node reversenode =

reverse

(head.next)

;//將當前節點下乙個節點的next指標域指向自己

head.next.next = head;

//將當前節點的next指標域置空

head.next = null;

return reversenode;

}

建立乙個鍊錶:1-2-3-4-5,測試**與結果如下

linkedlist linkedlist =

newlinkedlist()

;for

(int i =

0; i <

5; i++

)system.out.

println

("反轉前:");

linkedlist.

list()

;linkedlist reverselist =

newlinkedlist

(reverse

(linkedlist.head));

system.out.

println

("反轉後:");

將a鍊錶:1-2-3-null與b鍊錶2-3-6-null合併為一張有序鍊錶,解題思路如下

**實現

/***

* 合併兩個有序鍊錶

* @param list1 鍊錶1

* @param list2 鍊錶2

* @return

*/public

static linkedlist mergetwolist

(linkedlist list1,linkedlist list2)

else

//每一次迴圈後都需要將cur後移

cur = cur.next;

}//退出迴圈時,至少有乙個鍊錶為空

//如果是第乙個鍊錶為空,那麼將cur.next指向第二個鍊錶的頭節點,由於第二個鍊錶本身就是有序的,所以合併後仍然有序

if(list1.head == null)

if(list2.head == null)

//由於temp的第乙個節點為min_value,為無效節點,所以返回下乙個

return

newlinkedlist

(temp.head.next)

;}

測試**及結果

linkedlist list1 =

newlinkedlist()

;list1.

addnode

(new

node(1

));list1.

addnode

(new

node(2

));list1.

addnode

(new

node(4

));system.out.

println

("鍊錶1為:");

list1.

list()

;linkedlist list2 =

newlinkedlist()

;list2.

addnode

(new

node(1

));list2.

addnode

(new

node(3

));list2.

addnode

(new

node(4

));system.out.

println

("鍊錶2為:");

list2.

list()

;linkedlist result =

mergetwolist

(list1,list2)

;system.out.

println

("合併結果為:");

返回鍊錶倒數第k個結點,結題思路如下

**實現

/***

* 獲取鍊錶的倒數第k個結點

* @param list 鍊錶

* @param k

* @return

*/public

static node getkthfromend

(linkedlist list,

int k)

node before = list.head;

node after = list.head;

for(

int i =

0;i < k;i++

) after = after.next;

}while

(after != null)

return before;

}

測試**以及結果,這裡的鍊錶使用上面合併鍊錶的結果

linkedlist result =

mergetwolist

(list1,list2)

; system.out.

println

("合併結果為:");

result.

list()

; system.out.

println

("倒數第3個結點值為:"

資料結構 單鏈表相關知識

1 建立乙個單鏈表 實現思路 首先,定義乙個頭結點 l 為其在記憶體中開闢一段空間並將指標域指標指向null 其次,生成乙個新結點p,將要插入的資料元素儲存到結點的資料域,並將其指標域指標指向頭結點 l 指向的結點 或null 最後,將新結點p插入到表頭。隨機產生n個元素的值,建立帶頭結點的單鏈線性...

資料結構 單鏈表相關習題3

解題思路 兩煉表若相交,則其最後乙個節點必定相同。所以遍歷得出兩鍊錶的尾節點可得知兩鍊錶是否相交。若兩鍊錶相交,則求出兩鍊錶長度,相減得其差值len。較長鍊錶先向後遍歷len次,隨後兩鍊錶同時向後遍歷。直到出現兩值相同時,該節點即為相交點。判定兩個鍊錶是否相交,並求出交點 linknode hasc...

Go語言 資料結構 單鏈表相關操作

一般來說,為了比較好的對單鏈表進行增刪該查操作,會設定乙個頭節點來標識煉表頭,這個節點本身不存放資料。如下 package main import fmt 定義乙個heronode type heronode struct 給鍊錶插入乙個結點,在單鏈表的最後加入 func insertheronod...