1. 程式人生 > >劍指offer系列(16):反轉連結串列

劍指offer系列(16):反轉連結串列

題目描述

輸入一個連結串列,反轉連結串列後,輸出新連結串列的表頭。

樣例

輸入: 1->2->3->4->5->NULL
輸出: 5->4->3->2->1->NULL

思路分析

雙指標法,pre指標用於使原連結串列斷鏈,指向反向,next指標用於節點的移動

程式碼及結果

public ListNode ReverseList(ListNode head) {
		if (head == null) {
			return null;
		}
		ListNode pre = null;
		ListNode next = null;
		while (head != null) {
			next = head.next;
			head.next = pre; //斷鏈
			pre = head;
			head = next;
		}
		return pre;
    }