数据结构(一):顺序表

来源:互联网 发布:开源地面站 安卓源码 编辑:程序博客网 时间:2024/05/17 02:08
1. 线性表
分为顺序表和链表
顺序表用数组实现,插入和删除会引起大量元素的移动, 链表用包含Node内部类的LinkedList类实现, 用引用代替指针
public class SingleLinkedList<E> implements List<E>{private Node head; private int length = 0;public SingleLinkedList(){ this.head = new Node(); //初始化头指针(data=null,prior=null)}@Overridepublic void clear() {for(Node node = head.next;node != null;){Node x = node.next;node.data = null;node.next = null;node = x;}}@Overridepublic int indexOf(E e) throws Exception {if(length ==0)throw new Exception("链表为空");int index = 0;Node n = head.next;while(n!=null && n.data != e){index++;n = n.next;}if (n!=null)return index;return -1;}@Overridepublic void insert(int index, E e) throws Exception {if (index>length)throw new Exception("超出链表范围");int j = 0;for(Node n = head;n!=null;){if(j!=index){n = n.next;j++;}else{Node newNode = new Node(e); //创建新节点newNode.next = n.next;n.next = newNode;break;}}length ++;}@SuppressWarnings("unchecked")@Overridepublic E get(int index) {if (index > length-1)throw new RuntimeException("超出链表范围");Node n = head.next;for(int j=0;j<=length-1;j++){if(j == index){return (E)n.data;}else{n = n.next;}}return null;}@Overridepublic boolean isEmpty() {return head.next == null;}@Overridepublic int length() {Node n = head.next;int length = 0;while(n != null){n = n.next;length ++;}return length;}@Overridepublic void remove(int index) throws Exception {if (index>length-1)throw new Exception("超出链表范围");int j = 0;for(Node n = head;n!=null;){if(j!=index){n = n.next;j++;}else{Node node = n.next;n.next = node.next;node = null;break;}}length --;}@Overridepublic void show() {Node n = head.next;while(n != null){System.out.print(n.data+",");n = n.next;}System.out.println();}class Node{private Object data;private Node next;public Node(){// 用与初始化head指针this.data = null;this.next = null;}public Node(Object o){ //用于构造新节点this.data = o;this.next = null;}public Object getData() {return data;}public void setData(Object data) {this.data = data;}public Node getNext() {return next;}public void setNext(Node next) {this.next = next;}}public static void main(String[] args) throws Exception {SingleLinkedList<Integer> ss = new SingleLinkedList<Integer>();ss.insert(0, 1);ss.insert(1, 2);System.out.println(ss.length);System.out.println(ss.get(1)+"sssssss");;ss.remove(1);ss.show();}}

0 0
原创粉丝点击