链表是一种物理存储单元上非连续、非顺序的存储结构,数据元素的逻辑顺序是通过链表中的指针链接次序实现的。链表由一系列结点(链表中每一个元素称为结点)组成,结点可以在运行时动态生成。
单向节点Node实例:
public class NodeTest { public static void main(String[] args){ Node node1 = new Node("node1"); Node node2 = new Node("node2"); Node node3 = new Node("node3"); //构建链表 node1.next = node2; node2.next = node3; System.out.println(node1.next.next.data); //插入一个节点 Node node4 = new Node("node4"); node4.next = node1.next; node1.next = node4; System.out.println(node1.next.next.next.data); } } class Node{ String data; Node next; public Node(String data){ this.data = data; } }
双向节点Node类似于单向节点Node,只是在节点声明中多了一个指向前一个节点的指针。
public class NodeTest { public static void main(String[] args){ Node node1 = new Node("node1"); Node node2 = new Node("node2"); Node node3 = new Node("node3"); //构建链表 node1.next = node2; node2.previous = node1; node2.next = node3; node3.previous = node2; node3.next = node1; node1.previous = node3; System.out.println(node1.next.previous.data); //插入一个节点(插入一个节点需要修改四个指针) Node node4 = new Node("node4"); node4.next = node1.next; node1.next.previous = node4; node4.previous = node1; node1.next = node4; System.out.println(node1.next.next.data); } } class Node{ Node previous; String data; Node next; public Node(String data){ this.data = data; } }
原文地址:http://zlfwmm.blog.51cto.com/5892198/1708495