遍历: 将一个集合中的每一个元素进行获取并查看
一、循环遍历
- 数组循环遍历
var arr = [1, 2, 3, 4, 5, 6, 7];
function bianLiArr(arr){
if(arr === null) return;
for(let i = 0; i < arr.length; i ++){
console.log(arr[i]);
}
}
- 链表循环遍历
function Node(value){
this.value = value;
this.next = null;
}
const node1 = new Node(1);
const node2 = new Node(2);
const node3 = new Node(3);
node1.next = node2;
node2.next = node3;
function bianLiLink(root){
let temp = root;
while(true){
if(temp === null){
break;
}else {
console.log(root.value)
temp = root.next;
}
}
}
二、递归遍历
- 数组递归遍历(不常用)
var arr = [1, 2, 3, 4, 5, 6, 7];
function bianLiArr(arr, i){
if(arr === null || arr.length <= i) return; // 出口(递归遍历,必须有出口,否则会一直调用)
console.log(arr[i]);
bianLiArr(arr, i + 1);
}
- 链表递归遍历(常用)
function Node(value){
this.value = value;
this.next = null;
}
const node1 = new Node(1);
const node2 = new Node(2);
const node3 = new Node(3);
function bianLiLink(root){
if(root === null) return; // 出口(递归遍历,必须有出口,否则会一直调用)
console.log(root.value);
bianLiLink(root.next);
}