Java编程题——简单实现List操作

实现一些List的基本操作:

package List;

public class Node {
    public int val;
    public Node next;

    public Node(int val) {
        this.val = val;
    }

    @Override
    public String toString() {
        return " " + this.val;
    }
}
package List;

public class Main {

    public static Node creatList(){
        Node a = new Node(1);
        Node b = new Node(2);
        Node c = new Node(3);
        Node d = new Node(4);
        Node e = new Node(5);
        a.next = c;
        c.next = e;
        e.next = d;
        d.next = b;
        return a;
    }

    public static void main(String[] args) {
        Node head = creatList();
        // 1.
        System.out.println("打印链表的每个元素:");
        for (Node cur = head; cur != null; cur = cur.next){
            System.out.print(cur + " ");
        }
    }
}

在这里插入图片描述
测试2:

    public static void main(String[] args) {
        Node head = creatList();
        System.out.println("找到链表的最后一个结点:");
        Node cur = head;
        while (cur != null && cur.next != null){
            cur = cur.next;
        }
        System.out.println(cur.val);
    }

在这里插入图片描述
测试3:

    public static void main(String[] args) {
        Node head = creatList();
        System.out.println("找到链表的倒数第二个结点:");
        Node cur = head;
        while (cur != null && cur.next != null && cur.next.next != null){
            cur = cur.next;
        }
        System.out.println(cur.val);        
    }

在这里插入图片描述
测试4:

    public static void main(String[] args) {
        Node head = creatList();
        System.out.println("找到链表的倒数第二个结点:");
        Node cur = head;
        while (cur != null && cur.next != null && cur.next.next != null){
            cur = cur.next;
        }
        System.out.println(cur.val);        
    }

在这里插入图片描述
测试5:

    public static void main(String[] args) {
        Node head = creatList();
        System.out.println("计算链表中元素的个数:");
        int count = 0;
        for (Node cur = head; cur != null; cur = cur.next){
            count++;
        }
        System.out.println(count);                
    }

在这里插入图片描述
测试6:

    public static void main(String[] args) {
        Node head = creatList();
        System.out.println("找到链表中是否包含某个元素:");
        int findVal = 5;
        int index = 1;
        Node cur = head;
        for (; cur != null; cur = cur.next){
            if (cur.val == findVal){
                break;
            }
            index++;
        }
        if (cur == null){
            System.out.println("未找到为 " + findVal + " 的值");
        }else {
            System.out.println("已找到为 " + findVal + " 的值");
            System.out.println("该值在链表的第 " + index + " 位");
        }              
    }

在这里插入图片描述

当 findVal 为 0 时:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值