線性資料結構的遍歷
阿新 • • 發佈:2020-01-09
// 陣列的遍歷
// 建立一個數組
arr = [1, 2, 3, 4, 5, 6]
const traverseArr = arr => { // 遍歷陣列的方法
if (arr === null) { // 判空,如果當前陣列為空,直接結束
return
}
for (const item of arr) { // 陣列屬於可迭代物件,可以使用for-of迴圈進行遍歷
console.log(item)
}
}
traverseArr(arr)
console.log('----------------') // 華麗的分割線
// 連結串列的遍歷
class Node { // 建立一個節點的類
constructor(value){
/*
* 連結串列的每一個節點都由兩部分組成
* 第一部分是該節點的值
* 第二部分是該節點的指向
* */
this.value = value
this.next = null
}
}
// 建立節點
const node1 = new Node(1)
const node2 = new Node(2)
const node3 = new Node(3)
const node4 = new Node(4)
const node5 = new Node(5)
const node6 = new Node(6)
// 將每一個節點產穿成一個串
node1.next = node2
node2.next = node3
node3.next = node4
node4.next = node5
node5.next = node6
/*
* 建立一個遍歷連結串列的方法
* 引數位要遍歷連結串列的根節點
* */
const traverseLink = root => {
// 建立一個變數temp儲存當前變數
let temp = root
while (true) { // 在不知道連結串列長度的情況下,使用while迴圈進行遍歷
if (temp !== null) { // 如果當前節點存在,則打印出當前節點的值
console.log(temp.value)
} else { // 如果當前節點不存在,說明遍歷結束,跳出迴圈
break
}
// 每次遍歷之後,temp向後移一位
temp = temp.next
}
}
traverseLink(node1)
console.log('-----------------')
// 使用遞迴遍歷連結串列
const recursionLink = root => {
if (root === null) { // 如果當前節點位空,結束遍歷
return
}
console.log(root.value) // 列印當前節點的值
recursionLink(root.next) // 遞迴當前節點的下一個節點
}
recursionLink(node1)