链表的插入、修改、删除、遍历--java

来源:互联网 发布:java图形界面插件 编辑:程序博客网 时间:2024/06/05 08:41
package List;public class ListNode {private class Node {          private Object obj;          private Node next = null;                    Node(Object obj){              this.obj = obj;          }      } private Node first = null;// 插入操作public void insert(Object obj) {Node node = new Node(obj);node.next = first;first = node;}// 删除public Object deleteFirst() throws Exception{if (first == null) {throw new Exception("empty!"); }Node temp = first;first = first.next;return temp.obj;}// 遍历public void display(){   if(first == null)   System.out.println("empty"); Node cur = first; while (cur != null) { System.out.print(cur.obj.toString() + " -> "); cur = cur.next; } System.out.print("\n"); }// 判断是否为空public boolean isEmpty(){          return (first == null);      }// 查找某个结点public Object find(Object obj) throws Exception{ if(first == null)              throw new Exception("LinkedList is empty!"); Node cur = first;while (cur != null) {if (cur.obj.equals(obj)){return cur.obj;}cur = cur.next;}return null;}// 删除某个结点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 pre = first;Node cur = first.next;while (cur != null) {if (cur.obj.equals(obj)) {pre.next = cur.next;}pre = cur;cur = cur.next;}}}public static void main(String[] args) throws Exception {ListNode listNode = new ListNode();listNode.insert(1);listNode.insert(2);listNode.insert(3);listNode.insert(4);listNode.display();System.out.println(listNode.find(2));}}

阅读全文
0 0
原创粉丝点击