遍历单个链表
const head = {
'val':5,
'next':{
'val':4,
'next':{
'val':3,
'next':{
'val':2,
'next':{
'val':1,
'next':undefined
}
}
}
}
}
递归遍历
function ergodic(node) {
if(!node.next) { // 最后节点,单独处理
console.log(node)
return node
} else {
console.log(node)
return ergodic(node.next);
}
}
ergodic(head)
while 遍历
while 遍历可分为两种情况:
- 遍历全部节点
- 遍历非尾节点:最后节点,单独处理
遍历全部节点
function ergodic(node) {
while(node){
console.log('node',node)
node = node.next
}
}
ergodic(head)
遍历非尾节点
function ergodic(node) {
while(node.next){
console.log('node',node)
node = node.next
}
// 打印最后一个
console.log('node',node)
}
ergodic(head)
注意:如果链表是先赋值在进行遍历,则不会对原数据产生影响