LeetCode: Reverse Linked List Solution

Update head each iteration

Approach

Update head until the initial head is tail

  • Stay with the initial head
  • Update new head as the initial head's next
  • Each new updated head's next is the previous head
1Input: 1 (initial head) -> 2 -> 3 -> 4
2
3After iteration 1: 2 -> (1) -> 3 -> 4
4After iteration 2: 3 -> 2 -> (1) -> 4
5
6Output: 4 -> 3 -> 2 -> (1)

Implementation (iterative)

1var reverseList = function (head) {
2 const curr = head
3
4 while (curr && curr.next) {
5 let next = curr.next
6
7 curr.next = curr.next.next
8 next.next = head
9
10 head = next
11 }
12
13 return head
14}

Implementation (recursive)

1var reverseList = function (head) {
2 if (!head || !head.next) return head
3 const newHead = reverseList(head.next)
4 head.next.next = head
5 head.next = null
6 return newHead
7}

Comments

Loading comments...

Tags

leetcode

linked list

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Remove Linked List Elements

Keep next next

Previous Post

LeetCode: Linked List Cycle II

Same as LC 141, but different in return

HoningJS

Search Posts