刚刚看到个帖子标题提到单链表,突然想起来我好像从来没写过一个单链表的代码,琢磨了一下索性写了一个最简单的,顺便用了
泛型来提高适用性。
package com.iteye.bolide74.test;
public class SingleLinkedList {
public static void main(String[] args) {
List<Integer> list = new List<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
Note<Integer> head = list.head;
while (head.hasNext()) {
System.out.println(head.value);
head = head.next;
}
}
}
class Note<E> {
public E value;
public Note<E> next;
public Note(E val, Note<E> next) {
this.value = val;
this.next = next;
}
public boolean hasNext() {
return this.next != null;
}
}
class List<E> {
public Note<E> head;
public List() {
this.head = new Note<E>(null, null);
}
public void add(E val) {
this.head = new Note<E>(val, this.head);
}
}