Skip to content

Latest commit

 

History

History
42 lines (36 loc) · 894 Bytes

206. Reverse Linked List.md

File metadata and controls

42 lines (36 loc) · 894 Bytes

Difficulty : Easy

Related Topics : LinkedList


Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

Follow up:

  • A linked list can be reversed either iteratively or recursively. Could you implement both?

Solution

  • mine
    • Java
      • Runtime: 0 ms, faster than 100.00%, Memory Usage: 38.7 MB, less than 6.69% of Java online submissions
        // O(N)time
        // O(1)space
        public ListNode reverseList(ListNode head) {
            ListNode res = null;
            while(head != null){
                ListNode t = head;
                head =  head.next;
                t.next = res;
                res = t;
            }
            return res;
        }