单链式存储线性列表
线性表的链式存储结构的特点是用一组任意的存储单元存储线性表的数据元素,这组存储单元可以是连续的,也可以是不连续的
(图片来自网络,侵删)
存储单元由两部分组成,数据源和指针,数据源放数据,指针指向下个存储单元。LinkedList采用的就是链式存储线性表。
链式线性表的插入操作
链式线性表的删除操作
实现(主要实现单链表的插入、删除、获取长度功能)
public class Node { Object data; //结点数据 Node next; //下一个结点 static Node first; //头结点 static Node last; //尾结点 //构造结点 public Node() { super(); } //得到头结点方法 public static Node getFirst() { return first; } //修改头结点方法 public static void setFirst(Node first) { Node.first = first; } //得到尾结点方法 public static Node getLast() { return last; } //修改尾结点方法 public static void setLast(Node last) { Node.last = last; } //插入结点操作 public static void insert(Node node, int index) { if (index == 0) { //在头结点插入时 node.next = first; first = node; } else { //普通情况 int temp = 0; for (Node n = first; n != null; n = n.next) { temp++; if (index == temp) { node.next = n.next; n.next = node; } } } } //得到链表长度 public static int getLength() { int len = 0; for (Node n = first; n != null; n = n.next) { len++; } return len; } //删除结点操作 public static Node delete(int index) { Node node = null; if (index == 0) { //删除头结点时 first = first.next; } else if (index == getLength()) { //删除尾结点时 for (Node n = first; n != null; n = n.next) { n.next = last; } } else if (index > getLength()) { //传进来的结点位置超过了链表长度时 System.out.println("超出链表长度"); System.exit(0); } else { //普通情况 int temp = 0; for (Node n = first; n != null; n = n.next) { temp++; if (temp == index) { node = n.next; n.next = n.next.next; } } } return node; } public static void main(String[] args) { //创建结点对象 Node l1 = new Node(); Node l2 = new Node(); Node l3 = new Node(); Node l4 = new Node(); Node l5 = new Node(); Node l6 = new Node(); Node.setFirst(l1); //设置初始链表头结点 Node.setLast(l5); //设置初始链表尾结点 //设置结点的data l1.data = "aaa"; l2.data = "bbb"; l3.data = "ccc"; l4.data = "ddd"; l5.data = "eee"; l6.data = "fff"; //链接结点 l1.next = l2; l2.next = l3; l3.next = l4; l4.next = l5; System.out.println("当前链表:"); for (Node i = first; i != null; i = i.next) { System.out.print(i.data + " "); } System.out.println(); System.out.println("链表长度:" + getLength()); System.out.println("头结点:" + getFirst().data); System.out.println("尾结点:" + getLast().data); insert(l6, 0); System.out.println("插入结点后,当前链表:"); for (Node i = first; i != null; i = i.next) { System.out.print(i.data + " "); } System.out.println(); delete(5); System.out.println("删除结点后,当前链表:"); for (Node i = first; i != null; i = i.next) { System.out.print(i.data + " "); } System.out.println(); } }
与顺序表的主要区别
链式线性表删除和插入效率高,查询效率低
顺序表查询效率高,删除和插入效率低。