Skip to content

Instantly share code, notes, and snippets.

@belichuk
Last active April 26, 2023 17:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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 6, 2023

if (node && node.next) { looks like a redundant check

@belichuk
Copy link
Author

Ok, let's try to remove the redundant check and execute

let myList = new List('c++');

myList.reverse().print();

Result

TypeError: Cannot create property 'next' on string 'c++'
    at List.reverse (/tmp/list.js:36:27)
    at Object.<anonymous> (/tmp/list.js:65:8)
    at Module._compile (node:internal/modules/cjs/loader:1254:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1308:10)
    at Module.load (node:internal/modules/cjs/loader:1117:32)
    at Module._load (node:internal/modules/cjs/loader:958:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:23:47

@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