单链表相关操作

来源:互联网 发布:四大洋的面积最新数据 编辑:程序博客网 时间:2024/05/20 14:23
package Tes;public class LinkList {// 纸上得来终觉浅,绝知此事要躬行。private class Node {private Object obj;// 使用object,可以操作不同类型的数据。值域private Node next = null;// 指针域public Node(Object obj) {this.obj = obj;}}private Node first = null;// 建立一个空表头private int key = 0;//记录操作位置/*public boolean isEmput() { * return (first == null); */}/* * addFirst()、deteleFirst()添加和删除一个表头,时间复杂度为O(1) * find()、remove()时间复杂度为O(N),平均查找N/2 * add(),reverse(),display() */public void addFirst(Object obj) {Node node = new Node(obj);node.next = first;first = node;}public Object deteleFirst() throws Exception {// 操作数据最好都要使用try什么的if (first == null) {throw new Exception("The first is Empty");}Node temp = first;first = first.next;return temp.obj;}public Object find(Object obj) throws Exception {if (first == null)throw new Exception("LinkedList is Empty!");Node current = first;while (current != null) {if (current.obj.equals(obj)) {return current.obj;}current = current.next;}return null;}public void add(int index, Object obj) {Node node = new Node(obj);Node current = first;Node previous = first;while (key != index) {previous = current;current = current.next;key++;}node.next = current;previous.next = node;key = 0;}public void add(Object obj){//顺序添加数据Node node = new Node(obj);Node current = first;Node previous = first;while (current != null) {previous = current;current = current.next;key++;}node.next = current;previous.next = node;}public void remove(Object obj) throws Exception {if (first == null)throw new Exception("LinkedList is Empty!");if (first.obj.equals(obj)) {first = first.next;} else {Node previous = first;Node current = first.next;while (current != null) {if (current.obj.equals(obj)) {previous.next = current.next;}previous = current;current = current.next;}}}public void remove(int index) throws Exception{if (first == null)throw new Exception("LinkedList is Empty!");Node previous = first;Node current = first.next;while (key != index) {if (current != null) {previous.next = current.next;}previous = current;current = current.next;key++;}key = 0;}public Node reverse() {//链表反转if (first == null || first.next == null) {return first;}Node previous = first;Node current = first.next;while (current != null) {Node reverseNode = current.next;current.next = previous;previous = current;current = reverseNode;}first.next = current;first = previous;return first;}public void display() {if (first == null) {System.out.println("The LinkList is Empty");}Node current = first;while (current != null) {System.out.print(current.obj.toString() + " -> ");current = current.next;}System.out.println();}public static void main(String[] args) throws Exception {LinkList mLinkList = new LinkList();mLinkList.addFirst(1);mLinkList.addFirst(2);mLinkList.addFirst(3);mLinkList.add(2, 5);mLinkList.display();mLinkList.reverse();mLinkList.display();mLinkList.remove(2);mLinkList.display();}}
0 0