乐闻世界logo
搜索文章和话题

How can I reverse a linked list with javascript?

1个答案

1

In JavaScript, reversing a linked list is a common algorithmic problem that involves rearranging the nodes such that the first node becomes the last and vice versa. This operation typically requires reversing the direction of the links between nodes.

Assume we have a simple definition of a singly linked list node class as follows:

javascript
class ListNode { constructor(value) { this.val = value; this.next = null; } }

Next, we will write a function to reverse the linked list. This function takes the head node of the linked list as input and returns the new head node (which is the original tail node). The fundamental approach involves traversing the original list and sequentially modifying each node's next pointer to reference the preceding node. By defining a variable prev to track the previous node, initialized to null, since the next of the new head node (the original tail) must be null.

Here is the implementation code:

javascript
function reverseList(head) { let prev = null; // Initial value: no previous node let current = head; // Start from the head node while (current !== null) { let next = current.next; // Temporarily save the next node current.next = prev; // Point current to the previous node prev = current; // Move prev forward current = next; // Move current forward } return prev; // prev becomes the new head node }

Example: Assume we have a linked list 1 -> 2 -> 3 -> null. After calling reverseList, it should become 3 -> 2 -> 1 -> null.

Complexity Analysis:

  • Time complexity: O(n), as we traverse the list once, where n is the length of the list.
  • Space complexity: O(1), since we only use a few auxiliary variables.

This method is intuitive and efficient. In practical development, this technique is highly useful when handling linked list problems.

2024年6月29日 12:07 回复

你的答案