算法1
看一個算法題目 node
輸入一個鏈表,從尾到頭打印鏈表每一個節點的值。算法
這個題目我本地調試了一下 分享一下 又好的能夠補充
鏈表我就很少說了 單鏈表 雙鏈表 循環鏈表 看個圖吧數組
利用數組
我看到這個題目時候第一想法是數組 搞多了這種反轉的 數組是第一個想到的來看下解法bash
function CreateNode(value) {
this.value = value
this.next = null
} //搞了一個鏈表
CreateNode.prototype.setNext = function(node) {
this.next = node
return node
}
CreateNode.prototype.reverse = function() {
var arr = [] //這裏目的是把鏈表的value push到數組
var data = this
while(data) {
arr.push(data.value) //這裏能夠直接arr.unshift(data.value)
data = data.next
}
return arr
}
var one = new CreateNode(1) //CreateNode {value: 1, next: null}
var two = new CreateNode(2)
var three = new CreateNode(3)
one.setNext(two).setNext(three) // CreateNode {value: 1, next: CreateNode} 這裏已經搞了一個鏈表
console.log(one.reverse().reverse()) // [3,2,1]複製代碼
上面是首先想到的解法 將單鏈表的節點值push 到數組 有好的想法 能夠補充數據結構