reorder linked list without creating a new one

Viewed 45

community! My problem is that I must order a linked list in such a way that a new one is not created, but the same one is returned. For example, if I have: Head --> [8] --> [15] --> [1] should I return Head --> [1] --> [8] --> [15] My code right now, probably my code is awful and incorrect, but I'm new and I couldn't find the answer. Thanks for your time!

LinkedList.prototype.orderList = function() {
  //temporary node to swap the element
  let current = this.head;

  if (LinkedList.value === null) return "Empty";
  if (LinkedList.next.value === null) return "Orderer list"

  while (this.head.next.value !== null) {
    for (let i; i < LinkedList.length; i++)
      if (LinkedList.head.value > LinkedList.head.next.value) {
        current = LinkedList.head;
      } else if (linkedList.LinkedList.head.next.value)
      current = linkedList.head;
  }
};
1 Answers

I did the classic simple sort (or bubble Sort). The one where i goes to n - 1 and j goes from i + 1 to n. It worked.

function Node(value) {
  this.value = value || null;
  this.next = null;
}

function print(list) {
  var head = list;
  var arr = [];
  while (head) {
    arr.push(head.value);
    head = head.next;
  }
  console.log("" + arr)
}
var list = new Node(3);
list.next = new Node(9);
list.next.next = new Node(6);
list.next.next.next = new Node(2);

function sort(list) {
  if (!list || !list.next) {
    return;
  }

  for (var i = list; i.next != null; i = i.next) {

    for (var j = i.next; j != null; j = j.next) {
      if (i.value > j.value) {
        var temp = i.value
        i.value = j.value
        j.value = temp;
      }
    }
  }
}

print(list)
sort(list)
print(list)

Related