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));
}
}
链表的插入、修改、删除、遍历--java
最新推荐文章于 2023-09-12 00:00:35 发布