• 遍历:将一个集合中的每一个元素进行获取并查看
  • 数组常用for循环,因为数组一般都是知道长度的
  1. var arr = [1,2,3,4,5];
  2. function find(arr){
  3. if (arr === null) return;
  4. <!--算法的写法中不允许出现报错行为,该严谨性判断须加上,常规编程中可以不添加该判断-->
  5. for(var i = 0; i < arr.length; i++){
  6. consoe.log(arr[i]);
  7. }
  8. }
  9. //运行find
  10. find(arr);
  11. //然后创建一个链表//
  12. function Node(value){
  13. this.value = value;
  14. this.next = null;
  15. }
  16. var node1 = new Node(1);
  17. var node2 = new Node(2);
  18. var node3 = new Node(3);
  19. var node4 = new Node(4);
  20. var node5 = new Node(5);
  21. node1.next = node2;
  22. node2.next = node3;
  23. node3.next = node4;
  24. node4.next = node5;
  25. <!--遍历Node-->
  26. function findNode(root){
  27. <!--传递链表只能传递根节点-->
  28. var temp = root;
  29. <!--不知道循环长度的时候使用while循环-->
  30. while(true){
  31. if(temp !== null){
  32. console.log(temp.value)
  33. }else{
  34. break;
  35. }
  36. temp temp.next;
  37. }
  38. }
  39. findNode(node1);
  40. <!--打印的是12345;-->
  41. findNode(node2);
  42. <!--打印的事2345;因为在此链表中,根节点会从node2的地方开始;找不到node1-->

递归遍历(算法学习中较重要)

  1. var arr = [1,2,3,4,5,6,7,8];
  2. function find(arr, i){
  3. if(arr === null || arr.length <= i) return;
  4. console.log(arr[i]);
  5. find(arr, i + 1);
  6. }
  7. <!--运行find,此时的递归方式传递两个参数,第一个是遍历的数组,第二个是起始位置-->
  8. find(arr, 0);
  9. <!--创建一个链表-->
  10. function Node(value){
  11. this.value = value;
  12. this.next = null;
  13. }
  14. var node1 = new Node(1);
  15. var node2 = new Node(2);
  16. var node3 = new Node(3);
  17. var node4 = new Node(4);
  18. var node5 = new Node(5);
  19. node1.next = node2;
  20. node2.next = node3;
  21. node3.next = node4;
  22. node4.next = node5;
  23. <!--递归遍历,必须有出口(return),否则会出现死循环,一般先找出口,再写递归-->
  24. function findNode(root){
  25. if(root === null) return;
  26. console.log(root.value);
  27. <!--如果root为空直接返回;不为空则打印root的值;但是此时只能打印一个值;使用递归重新调用自身即可-->
  28. findNode(root.next);
  29. }
  30. findNode(node1);
  31. <!--打印的是12345;-->
  32. findNode(node2);
  33. <!--打印的事2345;因为在此链表中,根节点会从node2的地方开始;找不到node1-->

递归遍历链表常用,能够节省大量的开发时间;递归很少用于数组遍历;