单向链表的添加和遍历

38 阅读1分钟

头部添加

 public class SinglyLinkedList {
     // ...
     public void addFirst(int value) {
         this.head = new Node(value, this.head);
     }
 }
  • 如果 this.head == null,新增节点指向 null,并作为新的 this.head

  • 如果 this.head != null,新增节点指向原来的 this.head,并作为新的 this.head

    • 注意赋值操作执行顺序是从右到左

while 遍历

 public class SinglyLinkedList {
     // ...
     public void loop() {
         Node curr = this.head;
         while (curr != null) {
             // 做一些事
             curr = curr.next;
         }
     }
 }

for 遍历

 public class SinglyLinkedList {
     // ...
     public void loop() {
         for (Node curr = this.head; curr != null; curr = curr.next) {
             // 做一些事
         }
     }
 }
  • 以上两种遍历都可以把要做的事以 Consumer 函数的方式传递进来

    • Consumer 的规则是一个参数无返回值,因此像 System.out::println 方法等都是 Consumer
    • 调用 Consumer 时,将当前节点 curr.value 作为参数传递给它