您的位置:首页 > 职场人生

面试题5:从头到尾打印链表

2017-05-09 19:24 204 查看

剑指Offer面试题5:从头到尾打印链表(JS实现)

题目描述:输入一个链表的头结点,从头到尾反过来打印出每个结点的值。

//栈
function Stack() {
var arr = [];
this.push = function(element) {
arr.push(element);
};
this.pop = function(){
return arr.pop();
};
this.isEmpty = function() {
return arr.length === 0;
}
}

function LinkList() {
var Node = function(element) {
this.element = element;
this.next = null;
}
length = 0;
var head = null;

//在结尾插入元素
this.append = function(element) {
var node = new Node(element),
current;
if(head === null) {
head = node;
}else {
current = head;
while(current.next) {
current = current.next;
}
current.next = node;
}
length++;
};

//从尾到头打印节点
this.PrintListReversingly = function(){
var stack = new Stack(),
current = head,
str = '';
while(current) {
stack.push(current.element);
current = current.next;
}
while(!stack.isEmpty()){
str += stack.pop();
}
return str;
}
};

var list = new LinkList();
list.append(15);
list.append(10);
list.append(8);
list.append(6);
list.append(3);
console.log(list.PrintListReversingly());
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息