java笔记之双向链表的简单模拟

韩顺平-零基础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);

    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值