转自:http://blog.csdn.net/haijing1995/article/details/71492638
//栈
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());
运行结果:
![图片.png](http://upload-images.jianshu.io/upload_images/5623231-84843bfe74ab5bed.png?imageMogr2/auto-orient/strip%7CimageView2/2/w
/1240)
完整的打印一遍链表(添加删除等方法):
https://www.bbsmax.com/A/1O5E88LrJ7/
题目描述
输入一个链表,从尾到头打印链表每个节点的值。
从尾到头打印链表:
方法一:
/*function ListNode(x){
this.val = x;
this.next = null;
}*/
function printListFromTailToHead(head)
{
// write code here
rs = []
if (head == null){
return rs;
}else{
l = head;
while (l.next != null)
{
rs.push(l.val);
l = l.next;
}
rs.push(l.val);
return rs.reverse()
}
}
方法二:
function printListFromTailToHead(head)
{
// write code here
var arr = []
while(head) {
arr.unshift(head.val)
head = head.next
}
return arr
}