定义一个单向链表,定义删除所有素数节点的函数

链表问题

该题目主要考察对链表的理解。难度:适中

代码如下
要点:

1. 构造节点类
2. 头节点 dummyHead 的使用
3. 工作指针使用以及指针的移动
4. 判断已到达链表尾部

public class ListConstruction {
    public static void main(String[] args) {
        Node node = new Node(3);
        node.next = new Node(5);
        node.next.next = new Node(7);
        node.next.next.next = new Node(9);
        Node nodelala = Node.deleteSushu(node);
        while (nodelala != null) {
            System.out.println(nodelala.data);
            nodelala = nodelala.next;
        }
    }
}

class Node {
    int data;
    Node next;

    public Node(int x) {
        this.data = x;
    }

    public static Node deleteSushu(Node node) {
        Node dummyHead = new Node(0);
        Node workPointer = dummyHead;
        while (node!= null) {
            int x = node.data;
            if (isSushu(x)) {
                node = node.next;
            } else {
                workPointer.next = new Node(x);
                workPointer = workPointer.next;
                node = node.next;
            }
        }
        return dummyHead.next;
    }

    private static boolean isSushu(int x) {
        for (int i = 2; i < x; i++) {
            if (x % i == 0)
                return false;
        }
        return true;
    }
}

在整个过程中加强理解了链表递归定义的特性。综合使用头指针,工作指针,以及node 指针(原链表)加深了对链表的理解。

题目最后的各个节点的整数值从链头到链尾按照不增顺序排列在这里有什么意义吗?恳请各位对我的代码做出指正。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值