韩顺平-零基础30天学java的笔记。
1.模拟一个简单的双向链表
class Node {
public Node prev;
public Node next;
public Object item;
public Node(Object item) {
this.item = item;
}
@Override
public String toString() {
return "Node name=" + item;
}
}
public class LinkedList01 {
public static void main(String[] args) {
Node bob = new Node("bob");
Node tom = new Node("tom");
Node milan = new Node("milan");
Node smith = new Node("smith");
//1.连接四个结点,形成双向链表
bob.next = tom;
tom.next = milan;
milan.next = smith;
smith.prev = milan;
milan.prev = tom;
tom.prev = bob;
//2.定义头尾结点
Node first = bob;
Node last = smith;
//3.头指针遍历
while (true) {
if (first == null) {
break;
}
System.out.println(first);
first = first.next;
}
System.out.println("------尾指针遍历------");
//4.尾指针遍历
while (true) {
if (last == null) {
break;
}
System.out.println(last);
last = last.prev;
}
//5.链表进行添加数据-Cline克莱恩,milan后smith前
Node cline = new Node("Cline");
cline.next = smith;
cline.prev = milan;
smith.prev = cline;
milan.next = cline;
System.out.println("--------再次遍历首指针------");
//6.再次遍历-first再次指向bob
first = bob;
while (true) {
if (first == null) {
break;
}
System.out.println(first);
first = first.next;
}
System.out.println("--------再次遍历尾指针------");
last=smith;
while (true){
if(last == null){
break;
}
System.out.println(last);
last=last.prev;
}
}
}
2.模拟简单的数组加链表结构
class Node {
Object item;
Node next;
public Node(Object item, Node next) {
this.item = item;
this.next = next;
}
}
public static void main(String[] args) {
//1.创建一个数组,大小是Node
Node[] table = new Node[16];
// 2.创建结点
Node john = new Node("john", null);
table[2] = john;
Node jack = new Node("jack", null);
john.next = jack;
Node rose = new Node("Rose", null);
jack.next=rose;
System.out.println("table=" + table);
}