- 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();
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。