當創建一個鏈表後,鏈表只知道自己的下一個節點,而不知道自己的上一個節點,爲了能夠讓節點知道上一個節點,我們需要這樣做。
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(){
Node current = first; //這是用於遍歷的指針
Node temp = null; //用於存儲的指針
Node point = null; //用於交換的指針
System.out.println("反轉後的鏈表 : ");
while(current != null){
point = temp;
temp = current;
current = current.next;
temp.next = point;
}
current = temp; //得到反轉後的Head指針
while(current != null){
System.out.println(current.data);
current = current.next;
}
System.out.println();
}