LinkedList双向链表

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package Collection;
 
public class LinkedList01 {
    public static void main(String[] args) {
        //模拟简单的双向链表
        Node jack = new Node("jack");
        Node tom = new Node("tom");
        Node mark = new Node("mark");
        //连接三个节点,形成双向链表
        //jack指向tom,tom指向mark,
        jack.next = tom;
        tom.next = mark;
        mark.prev = tom;
        tom.prev = jack;
        //first指向jack,做为双向链表的头节点;
        //last直系那个mark,做为双向链表的尾节点;
        Node first = jack;
        Node last = mark;
        System.out.println("从头到尾进行遍历==========");
        //从头到尾进行遍历
        while (true) {
            if (first == null){
               break;
            }
            //输出信息
            System.out.println(first);
            first= first.next;
        }
        System.out.println("从尾到头进行遍历========");
        //从尾到头进行遍历
        while (true) {
            if (last == null){
                break;
            }
            //输出信息
            System.out.println(last);
            last= last.prev;
        }
 
        System.out.println("添加一个smith数据===============");
 
        //要求在双向链表中添加一个对象/数据,如在jack和Tom之间添加smith
        //先添加一个node对象,名字为smith
        Node smith = new Node("smith");
        jack.next = smith;
        tom.prev= smith;
        smith.next= tom;
        smith.prev=jack;
 
         first = jack;
        //从头到尾进行遍历
        while (true) {
            if (first == null){
                break;
            }
            //输出信息
            System.out.println(first);
            first= first.next;
        }
            last =mark;
        System.out.println("从尾到头进行遍历======================");
        //从尾到头进行遍历
        while (true) {
            if (last == null){
                break;
            }
            //输出信息
            System.out.println(last);
            last= last.prev;
        }
 
 
 
    }
}
 
//定义一个node类,node对象表示双向链表的一个节点
class Node {
    public Object item;//存放非数据
    public Node next;
    public Node prev;
 
    //创建一个构造器
    public Node(Object item) {
        this.item = item;
    }
 
    @Override
    public String toString() {
        return "Node name=" + item;
    }
}
  

 

posted @   捞月亮的渔夫  阅读(29)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示