Skip to content

Latest commit

 

History

History
49 lines (40 loc) · 1.09 KB

File metadata and controls

49 lines (40 loc) · 1.09 KB

Screen Shot 2022-08-30 at 15 42 35

Time complexity : O(n). Assume that nn is the list's length, the time complexity is O(n)O(n).

CPP

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode* prev = nullptr;
        ListNode* curr = head;

        while (curr) {
            ListNode* next = curr->next; 
            curr->next = prev;           
            prev = curr;                 
            curr = next;                 
        }

        return prev;
    }
};

Space complexity : O(1).

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var reverseList = function(head) {
  let [prev, current] = [null, head];
    while(current) {
        [current.next, prev, current] = [prev, current, current.next];
    }
    return prev;
};