Reverse Linked list

2018-08-05  本文已影响8人  超薄智能
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();

上一篇下一篇

猜你喜欢

热点阅读