美文网首页
Reverse Linked list

Reverse Linked list

作者: 超薄智能 | 来源:发表于2018-08-05 20:19 被阅读8次
  • single linked list
  • reverse linked list
  • traverse
  • recursion
function Node(data) {
  this.data = data;
  this.next = null;
}

function LinkedList() {
  this.head = null;
  this.tail = null;
  // this.numberOfValues = 0;
}

LinkedList.prototype.add = function(data){
  var node = new Node(data);

  if(!this.head){
      this.head = node;
      this.tail = node;
  }else{
      this.tail.next = node;
      this.tail = node; 
  }
}

LinkedList.prototype.traverse = function(){
    var res = [];
    var cursor = this.head;
    while(cursor){
        res.push(cursor.data);
        cursor = cursor.next;
    }
    return res;
}

LinkedList.prototype.traverseRecursly = function(cursor){
  if(!cursor){
    return;
  }else{
    // print data in ordered way
    console.log(cursor.data);
    // this.head.next.next.next ...
    this.traverseRecursly(cursor.next);
    // print data in reversed way
    //console.log(cursor.data);
  }
}

LinkedList.prototype.reverse = function(){
  var dataArr = this.traverse();
  var reversedList = new LinkedList();
  for(var i=dataArr.length-1; i>=0; i--){
      reversedList.add(dataArr[i]);
  }
  return reversedList;
}

LinkedList.prototype.reversePrev = function(){
    var reversedList = new LinkedList();
    var cursor = this.head;
    var prev = null;
    var curr = null;
    while(cursor){
      if(cursor == this.head){
        curr = _clone(cursor);
        curr.next = null;
        reversedList.tail = curr;
        prev = curr;
      }else if(cursor == this.tail){
        curr = _clone(cursor);
        curr.next = prev;
        reversedList.head = curr;
        
        return reversedList;
      }else{
        curr = _clone(cursor);
        curr.next = prev;
        reversedList.add(curr);
        prev = curr;
      }

      cursor = cursor.next;
    }
}

// Bad and simple way to do deep clone
// Q: does this really need and how to do this with address purely in C
function _clone(obj){
  return JSON.parse(JSON.stringify(obj))
}

LinkedList.prototype.print = function(){
    console.log(this);
}

var linkList = new LinkedList();
linkList.add(10);
linkList.add(20);
console.log(linkList.traverse());
console.log(linkList.reverse().traverse());
console.log(linkList.reversePrev().traverse());
linkList.traverseRecursly(linkList.head);
// linkList.print();

相关文章

网友评论

      本文标题:Reverse Linked list

      本文链接:https://www.haomeiwen.com/subject/accivftx.html