单向链表Java实现

public class SingleLinkedList {
    private int length; //链表节点的个数
    private Node head; //链表的头节点
    public SingleLinkedList() {
        length = 0;
        head = null;
    }
    // 链表的每个节点的数据结构描述类
    private class Node {
        private Object data; //每个节点的数据
        private Node next; //下一个节点的连接
        public Node(Object data) {
            this.data = data;
        }
    }

    //在链表的头部添加元素
    public Object addHead(Object obj) {
        Node newHead = new Node(obj); //1:定义1个新节点
        if(length == 0) {//2:如果链表为空,则该将节点设置为头节点
            head = newHead;
        } else {//3:设置当前插入的节点为头节点,并将其下一个节点指向原来的头节点
            newHead.next = head;
            head = newHead;
        }
        length++;// 4:链表的长度+1
        return obj;
    }
    //删除指定的元素,若删除成功则返回true
    public boolean delete(Object value) {
        if (length == 0) {
            return false;
        }
        Node current = head;
        Node previous = head;
        while (current.data != value) {
            if(current.next == null) {
                return false;
            }else {
                previous = current;
                current = current.next;
            }
        }
        //如果删除的节点是头节点
        if(current == head) {
            head = current.next;
            length--;
        }else {//删除的节点不是头节点
            previous.next = current.next;
            length--;
        }
        return true;
    }
    //查找指定的元素,如果找到了,则返回节点Node;如果找不到,则返回null
    public Node find(Object obj) {
        Node current = head;
        int tempSize = length;
        while (tempSize > 0) {
            if (obj.equals(current.data)) {
                return current;
            } else {
                current = current.next;
            }
            tempSize--;
        }
        return null;
    }
    //测试主方法
    public static void main(String[] args) {

        String[] letters = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
                "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
        SingleLinkedList singleLinkedList = new SingleLinkedList();
        for(String letter : letters) {
            singleLinkedList.addHead(letter);
        }
        singleLinkedList.delete("W");
        System.out.println(singleLinkedList.toString());
        Node u = singleLinkedList.find("U");
        System.out.println(u);
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值