劍指 Offer 24. 反轉鏈表
定義一個函數,輸入一個鏈表的頭節點,反轉該鏈表並輸出反轉後鏈表的頭節點。
示例:
輸入: 1->2->3->4->5->NULL
輸出: 5->4->3->2->1->NULL
限制:
0 <= 節點個數 <= 5000
1.迭代:
// 1.雙指針迭代(方法中循環遍歷,比如for/while)
public ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode cur = head;
ListNode next = null;
while (cur !=null) {
// 記錄了cur.next的位置
next = cur.next;
// 反轉指針位置
cur.next = pre;
// pre、cur指針移動一次
pre = cur; // pre移動到原來cur的位置
cur = next; // cur移動到原來cur.next的位置
}
return pre;
}
2.遞歸
// 2.遞歸
public ListNode reverseList1(ListNode head) {
// 1).用此遞歸到最後5,停止遞歸
// 2).遞歸返回到1時,上一輪設置了1的next爲null,停止遞歸
if (head==null || head.next==null) {
return head;
}
// cur爲遞歸到最後的一個節點,如1-2-3-4-5-null,停止遞歸後返回5
ListNode cur = reverseList1(head.next);
// 5之後返回上層的遞歸,此時head爲4
// head.next爲5,head.next.next爲5的下個節點 = 4
head.next.next = head;
// 將4節點原來的next置空,免得4下節點到5,而5剛纔賦到4成爲循環鏈表
head.next = null;
return cur;
}