Skip to content

Commit

Permalink
feat: 206. Reverse Linked List
Browse files Browse the repository at this point in the history
  • Loading branch information
gwbaik9717 committed Jan 19, 2025
1 parent 89edeec commit e7dc805
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions reverse-linked-list/gwbaik9717.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// Time complexity: O(n)
// Space complexity: O(n)

/**
* 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) {
const stack = [];

let temp = head;
while (temp) {
stack.push(temp.val);
temp = temp.next;
}

if (!stack.length) {
return null;
}

const popped = stack.pop();
const answer = new ListNode(popped);

temp = answer;
while (stack.length > 0) {
const popped = stack.pop();

temp.next = new ListNode(popped);
temp = temp.next;
}

return answer;
};

0 comments on commit e7dc805

Please sign in to comment.