思想:
利用unshift往前面添加元素
function LinkList() {
var Node = function(element) {
this.element = element;
this.next = null;
};
this.head = null;
this.length = 0;
if(typeof this.append != 'function') {
LinkList.prototype.append = function(element) {
var node = new Node(element);
if(this.head === null) {
this.head = node;
} else {
var currentNode = this.head;
while(currentNode.next) {
currentNode = currentNode.next;
}
currentNode.next = node;
}
this.length++;
};
LinkList.prototype.getHead = function(){
return this.head;
};
}
}
var linklist = new LinkList();
var arr = [1,2,3,4,5];
for(var i = 0; i < arr.length; i++) {
linklist.append(arr[i]);
}
var reversePrint = function(linklist) {
var head = linklist.getHead();
var result = [];
while(head) {
result.unshift(head.element);
head = head.next;
}
return result.join("->")
};
console.log(reversePrint(linklist));