ReverseLinkedList
Wed, Sep 28, 2022
閱讀時間 1 分鐘
reverse Linked List
positive
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode node = head;
ListNode next = null;
while(node != null){
next = node.next;
node.next = prev;
prev = node;
node = next;
}
head = prev;
return head;
}
recursive
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null) return head;
ListNode result = reverseList(head.next);
head.next.next = head;
head.next = null;
return result;
}