翻轉連結串列(非遞迴)
1. 問題描述:
給出一個連結串列,翻轉連結串列,返回翻轉後連結串列的頭結點
2. 我們也可以使用非遞迴的方式來進行翻轉連結串列,首先遍歷連結串列,使用一個指標pre記錄當前節點的前一個節點,使用當前節點的next指向前一個節點pre,即下一個元素的指標next指向前一個元素pre那麼就實現了連結串列的翻轉
這裡特別要注意的是pre.next不能賦值為空,當第一個元素的時候倒是沒有關係,但是在迴圈後面的元素pre是有指向的,指向的是前一個元素,假如你再修改的話那麼會導致前面形成的連結串列會斷掉,最後只會剩下兩個元素,所以不能夠寫下面的pre.next = null;這句程式碼,假如遍歷是從第二個元素開始的那麼應該在迴圈之前把第一個pre的next置為空即可
while(p != null){
temp = p.next;//pre.next = null;
p.next = pre;
pre = p;
p = temp;
}
3. 具體的程式碼如下:
public class Main {
private static class ListNode{
private ListNode next;
private Object value;
public ListNode(Object value) {
super();
this.value = value;
}
}
public static void main(String[] args){
int arr[] = {0, 6, 6, 7, 3, 3, 5, 3, 8, 9, 10};
//int arr[] = {0, 1};
ListNode head = new ListNode(arr[0]);
ListNode p = head;
for(int i = 1; i < arr.length; i++){
p.next = new ListNode(arr[i]);
p = p.next;
}
p = head;
while(p != null){
System.out.print(p.value+ " ");
p = p.next;
}
System.out.print("\n");
p = reverseLinkedList(head);
while(p != null){
System.out.print(p.value+ " ");
p = p.next;
}
}private static ListNode reverseLinkedList(ListNode node){
ListNode p = node.next;
ListNode pre = node;
pre.next = null;
ListNode temp;
while(p != null){
temp = p.next;
p.next = pre;
pre = p;
p = temp;
}
return pre;
}
}