單鏈表的反轉 三指標版

2021-10-02 10:31:26 字數 873 閱讀 2133

當建立乙個鍊錶後,鍊錶只知道自己的下乙個節點,而不知道自己的上乙個節點,為了能夠讓節點知道上乙個節點,我們需要這樣做。

1、建立三個指標 乙個是沿著原來的鍊錶進行遍歷,乙個儲存,乙個用於交換

2、進行將鍊錶反向的工作

比如: 原來鍊錶 0 -> 1 -> 2 -> 3 -> 4…-> n ->null;

用**來表示就是 0.next = 1 1.next = 2 2.next = 3 3.next = 4 等等

我們需要變成的是 n -> n-1 -> … -> 4 -> 3 -> 2 -> 1 -> 0 -> null

用**來表示就是 n.next = n-1 4.next = 3 3.next = 2 2.next = 1 1.next = 0 0.next = null

下面這塊**的三個指標

current : 遍歷指標

temp : 用於儲存的指標

point : 指向需要交換的值

比如第一輪while是這樣的

*剛開始 current = 0 temp = null point = null (我們想要的效果是 0.next = null) 所以最終想要得到的表示式是 current.next = point 但是為了進行下一輪的迴圈 可以用temp來代替current 讓 current繼續迭代 就是 temp.next = point

public

void

reverse()

current = temp;

//得到反轉後的head指標

while

(current != null)

system.out.

println()

;}

單鏈表反轉 java版

head a b c 變成 head c b a 我們可以用迴圈的方式去實現,遍歷一次鍊錶即可。1.用乙個臨時變數tmp儲存 a的下乙個元素b,a的next指向null,即 由頭變尾 head指向null。head null a b c tmp b 2.因為此時tmp就是b,所以將tmp指向tmp的...

單鏈表反轉 python版

如下 class node object def init self,elem,next none self.elem elem self.next next def reverselist head if head none or head.next none 若煉表為空或者僅乙個數就直接返回 r...

指標(三) 指標陣列

指標陣列定義 一維指標陣列的定義形式 型別名 陣列名 陣列長度 char p 5 乙個陣列,若其元素均為指標型別資料,稱為指標陣列,指標陣列中的每乙個元素都相當於乙個指標變數。指標陣列的初始化 使用位址為指標陣列初始化 char p 5 指標陣列和二級指標 int main char temp 定義...