Skip to content

Instantly share code, notes, and snippets.

@belichuk
Last active April 26, 2023 17:51
Show Gist options
  • Save belichuk/b9707d852ba751ec7bc0cf57114590b8 to your computer and use it in GitHub Desktop.
Save belichuk/b9707d852ba751ec7bc0cf57114590b8 to your computer and use it in GitHub Desktop.
reverse list javascript
class List {
constructor(head = null) {
this.head = head
}
insert(newNode) {
let node = this.head;
if (node==null) {
this.head = newNode;
return;
}
while (node.next) {
node = node.next;
}
node.next = newNode;
}
print() {
let node = this.head;
process.stdout.write("HEAD->")
while (node) {
process.stdout.write(node.data + "->");
node = node.next;
}
process.stdout.write("End\n");
}
reverse() {
let node = this.head,
prev = null,
next;
if (node && node.next) {
while (node) {
next = node.next;
node.next = prev;
prev = node;
node = next;
}
this.head = prev;
}
return this;
}
}
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
let myList = new List();
myList.insert(new Node(4));
myList.insert(new Node(3));
myList.insert(new Node(2));
myList.insert(new Node(1));
myList.insert(new Node(0));
myList.print();
myList.reverse().print();
@realsba
Copy link

realsba commented Apr 26, 2023

Please check

struct Node* reverseList(struct Node* head)
{
  Node* prev = nullptr;
  while (head != nullptr) {
    auto* tail = head->next;
    head->next = prev;
    prev = head;
    head = tail;
  }
  return prev;
}

It works fine with only while loop

@belichuk
Copy link
Author

Please check

struct Node* reverseList(struct Node* head)
{
  Node* prev = nullptr;
  while (head != nullptr) {
    auto* tail = head->next;
    head->next = prev;
    prev = head;
    head = tail;
  }
  return prev;
}

It works fine with only while loop

completely agree, It will work properly in C/C++. Using strictly typed language you have no chance to initialize Node with just a string. But JavaScript allows it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment