- 迭代法:
雙指針
;一個指針指向已經反轉鏈表的尾部
,一個指針指向待反轉鏈表的首部
,不斷遍歷即可
public ListNode reverseList(ListNode head) {
if(head==null||head.next==null) return head;
//已經反轉鏈表的尾部
ListNode pre = null;
//當前要反轉鏈表的頭部
ListNode cur = head;
//待反轉鏈表的下一節點
ListNode next = cur.next;
while(cur!=null){
next=cur.next;
cur.next=pre;
pre= cur;
cur = next;
}
return pre;
}
- 迭代
public ListNode reverseList(ListNode head) {
if(head==null||head.next==null) return head;
ListNode cur = reverseList(head.next);
head.next.next=head;
head.next=null;
return cur;
}