題目描述:
定義一個函數,輸入一個鏈表的頭結點,反轉該鏈表並輸出反轉後鏈表的頭結點。
思路分析:
-
遞歸法
該題可以用遞歸處理。一直遞歸到最後一個結點,然後翻轉最後一個結點,然後翻轉倒數第二個結點…返回之前的尾結點,即翻轉後的首結點。
參考代碼:
public static ListNode reverseList(ListNode head) {
if(head == null || head.next == null)return head;
ListNode root = reverseList(head.next);
head.next.next = head;
head.next = null;
return root;
}
-
迭代法:
設置3個指針pre,curr,next,分別表示前一個結點,當前節點,後一個結點,然後從前到後進行翻轉。
參考代碼:
public static ListNode reverseList(ListNode head) {
if(head == null || head.next == null)return head;
ListNode pre = null;
ListNode curr = head;
ListNode next = head.next;
while(next != null){
curr.next = pre;
pre = curr;
curr = next;
next = next.next;
}
curr.next = pre;
return curr;
}
(完)