/** * * 线性单链表 */ public class LinkedLinearList { private Node head; private int length;// 实际长度 /** * 初始化顺序表,长度为length */ public LinkedLinearList() { length = 0; head = new Node('0', null); length++; } /** * 将index位置赋值为c,会覆盖掉原值 * * @param index * @param c */ public void set(int index, char c) { Node node = head; int n = 0; while (n < index) { if (node.next == null) { node.next = new Node('0', null); length++; } node = node.next; n++; } if (node == null) { node = new Node(c, null); length++; } else { node.data = c; } } /** * 取得下标为index的值,若是为空返回ascii为零的字符 * * @param index * @param c * @return */ public char get(int index) { if (index > length - 1 || index < 0) { System.out.println("out of size exception!"); return 0; } else { Node node = head; int n = 0; while (n < index) { node = node.next; n++; } return node.data; } } /** * 在index位置插入c,不会覆盖掉原值 * * @param index * @param c */ public void insert(int index, char c) { if (index < 0) { System.out.println("out of size exception!"); return; } else { Node node = head; int n = 0; while (n < index - 1) { if (node.next == null) { node.next = new Node('0', null); length++; } else { node = node.next; } n++; } if (node.next == null) { node.next = new Node(c, null); } else { Node newNode = new Node(c, null); newNode.next = node.next; node.next = newNode; } length++; } } /** * 返回长度 * * @return */ public int length() { return length; } /** * 删除下标为index的元素 * * @param index */ public void delete(int index) { if (index > length - 1 || index < 0) { System.out.println("delete not exist element exception"); } else { Node node = head; int n = 0; while (n < index - 1) { if (node.next == null) { node.next = new Node('0', null); length++; } else { node = node.next; } n++; } node.next = node.next.next; length--; } } /** * 查找c元素,返回第一个找的c元素的下标,没有找到返回-1 * * @param c */ public int findChar(char c) { Node node = head; int n = 0; while (n < length - 1 && node != null) { if (node.data == c) return n; node = node.next; n++; } return -1; } public void show() { Node node = head; int n = 0; while (n < length && node != null) { System.out.print(node.data + ","); node = node.next; n++; } System.out.println(); } public static void main(String[] args) { LinkedLinearList lll = new LinkedLinearList(); lll.set(0, 'a'); lll.set(1, 'b'); lll.set(2, 'c'); lll.set(3, 'd'); lll.set(4, 'e'); lll.show(); lll.insert(2, 'f'); lll.show(); lll.delete(2); lll.show(); System.out.println(lll.length()); System.out.println(lll.findChar('c')); lll.set(0, 'z'); lll.show(); } class Node { char data; Node next; public Node(char data, Node next) { this.data = data; this.next = next; } } }