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

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值