夜殇、

线性数据结构的遍历
// 数组的遍历
// 创建一个数组
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)

posted on 2020-01-09 20:32  夜殇、  阅读(145)  评论(0编辑  收藏  举报