1 //单链表结点类 2 public class Node<T> { //单链表结点类,T指定结点的元素类型 3 4 public T data; //数据域,保存数据元素 5 public Node<T> next; //地址域,后任结点引用 6 7 //构造结点,data指定数据元素,next指定后继结点 8 public Node(T data, Node<T> next) { 9 this.data = data; 10 this.next = next; 11 } 12 13 public Node() { 14 this(null, null); 15 } 16 17 //返回结点对应的字符串 18 public String toString() { 19 return this.data.toString(); 20 } 21 22 //比较两个结点值是否相等,覆盖Object类的equals(obj)方法 23 public boolean equals(Object obj) { 24 return obj == this || obj instanceof Node && this.data.equals(((Node<T>) obj).data); 25 } 26 }
1 //循环单链表类,实现线性表接口 2 public class LoopLinkList<T> { 3 4 //头指针,指向循环单链表的头结点 5 public Node<T> head; 6 7 //默认构造方法,构造空循环单链表 8 public LoopLinkList() { 9 this.head = new Node<T>(); 10 this.head.next = this.head; ////创建头结点 11 } 12 13 //判断循环单链表是否空 14 public boolean isEmpty() { 15 return this.head.next == this.head; 16 } 17 18 //由element数组中的多个对象构造单链表。采用尾插入构造单链表 19 public LoopLinkList(T[] element) { 20 this(); //创建空单链表,只有头结点 21 Node<T> rear = this.head; //rear指向单链表最后一个结点 22 for (int i = 0; i < element.length; i++) { //若element==null,抛出空对象异常 23 //若element.length==0,构造空链表 24 rear.next = new Node<T>(element[i], this.head); //尾插入,创建结点链入rear结点之后 25 rear = rear.next; //rear指向新的链尾结点 26 } 27 } 28 29 //返回循环单链表长度,单链表遍历算法,O(n) 30 public int length() { 31 int i = 0; 32 for (Node<T> p = this.head.next; p != this.head; p = p.next) 33 i++; 34 return i; 35 } 36 37 //返回第i(≥0)个元素,若i<0或大于表长则返回null,O(n) 38 public T get(int i) { 39 if (i >= 0) { 40 Node<T> p = this.head.next; 41 for (int j = 0; p != this.head && j < i; j++) 42 p = p.next; 43 if (p != this.head) 44 return p.data; //p指向第i个结点 45 } 46 return null; //当i<0或大于表长时 47 } 48 49 //设置第i(≥0)个元素值为x。若i<0或大于表长则抛出序号越界异常;若x==null,不操作。O(n) 50 public void set(int i, T x) { 51 if (x == null) return; //不能设置空对象 52 Node<T> p = this.head.next; 53 for (int j = 0; p != this.head && j < i; j++) 54 p = p.next; 55 if (i >= 0 && p != this.head) 56 p.data = x; //p指向第i个结点 57 else throw new IndexOutOfBoundsException(i + ""); //抛出序号越界异常 58 } 59 }
1 public static void main(String args[]){ 2 3 Integer[] array=new Integer[]{12,25,55,78,99,-17}; 4 LoopLinkList<Integer> linkList =new LoopLinkList<Integer>(array); 5 6 int length=linkList.length(); 7 int a=linkList.get(5); 8 9 System.out.println("链表是否为空:"+linkList.isEmpty()); 10 System.out.println("链表长度是:"+length); 11 System.out.println("获取指定位置的数据是:"+a); 12 13 for(int i=0;i<length;i++) 14 System.out.println(linkList.get(i)); 15 16 linkList.set(1,200); 17 18 for(int i=0;i<length;i++) 19 System.out.println(linkList.get(i)); 20 }