链表常规操作 Java版本

本文详细介绍了使用Java手写链表的过程,包括节点添加、删除、长度计算、反转及环检测等功能。通过具体代码示例,展示了链表的基本操作和维护方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package suanfa.link;

public class MyLinkedList {
    Node head = null;

    public void addNode(Object e) {
        Node newNode = new Node(e);
        if (null == head) {
            head = newNode;
            return;
        }
        Node temp = head;
        while (temp.next != null) {
            temp = temp.next;
        }
        temp.next = newNode;
    }

    public boolean deleteNode(int index) {
        if (index < 0 || index >= length()) {// 待删除结点不存在
            return false;
        }

        if (index == 0) {
            head = head.next;
            return true;
        }
        Node preNode = head;
        Node curNode = preNode.next;
        int i = 1;
        while (curNode != null) {
            if (i == index) {
                preNode.next = curNode.next;
                return true;
            }
            preNode = preNode.next;
            curNode = curNode.next;
            i++;
        }
        return true;
    }

    public int length() {
        int length = 0;
        Node curNode = head;
        while (curNode != null) {
            length++;
            curNode = curNode.next;
        }
        return length;
    }

    void show() {
        Node curNode = head;
        while (curNode != null) {
            System.out.println(curNode.element);
            curNode = curNode.next;
        }
    }

    void reserve() {
        Node curNode = head;// 头结点
        Node preNode = null;// 前一个结点
        while (curNode != null) {
            Node nextNode = curNode.next;
            curNode.next = preNode;// 指针反转
            preNode = curNode;// 前结点后移
            curNode = nextNode;// 当前结点后移
        }
        head = preNode;
    }

    public boolean isRinged() {
        if (head == null) {
            return false;
        }
        Node slow = head;
        Node fast = head;
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (fast == slow) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        MyLinkedList linkedList = new MyLinkedList();
        linkedList.addNode("111");
        linkedList.addNode("222");
        // linkedList.addNode("333");
        // linkedList.addNode("333");
        linkedList.reserve();
        // System.out.println(linkedList.length());
        // linkedList.deleteNode(2);
        linkedList.show();

    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值