随机数、链表

一、随机数的产生
Math.Random产生[0, 1)之间的任意小数
Math.Random * (value + 1)产生[0, value + 1)之间的任意小数
(int)Math.Random * (value + 1) 产生[0, value]之间的任意整数

二、链表
1.链表的反转
(1)创建双向链表
需要一个头指针next,一个尾指针last
还要有一个值,通过构造方法传入Node

    public static class Node {
        Node last;
        Node next;
        int value;

        public Node(int data) {
            value = data;
        }


    }

(2)创建一个长度不大于len的双向链表
A.生成一个[0, len]的随机整数,判空;
B.size–的意思是,已经生成了一个头结点,再拿size去创建的剩余节点,这样节点的数量就会比size多一个,所以要减一个;
C.创建头结点,且因为要返回该头结点,所以另开一个结点pre进行相关操作
D.创建剩余结点,循环创建cur结点,让pre.next指向cur,cur.last指向pre,pre再移至cur,循环,创建cur结点,指向,移至。
E.最后返回head结点;

    public static Node generateRandomDoubleList(int len, int value) {
        int size = (int) (Math.random() * len + 1);
        if (size == 0) {
            return null;
        }
        size--;
        Node head = new Node((int) (Math.random() * (value + 1)));
        Node pre = head;

        while (size != 0) {
            Node cur = new Node((int) (Math.random() * (value + 1)));
            pre.next = cur;
            cur.last = pre;
            pre = cur;
            size--;
        }
        return head;

    }

(3)反转双向链表
A.将头指针head传进来,因为要返回新的头指针,返回值用Node;
B.需要两个额外的指针next和last,因为head相当于从头部移到尾部,所以head可以拿来操作;
C.,head不空的前提下,next先记录一下head.next的位置,head.next指向前一个结点last,head.last指向后一个结点,即指向next(这时记录的head.next派上用场),last记录一下head当前的位置,因为head要往后移了,head指向next,也可以指向head.last
D.最后应该返回last,因为在最后一次时,next = head.next = null,而最后head = next = null,所以应该返回记录了head值的last

    public static Node reverse(Node head) {
        Node last = null;
        Node next = null;
        while (head != null) {

            next = head.next;
            head.next = last;
            head.last = next;
            last = head;
            head = next;
        }
        return last;
    }

2.删除双向链表中指定的元素
首先是要返回一个头结点的,而头结点往后如果有一堆指定要删除的元素,那头结点是需要在开始就向后移动的,当移动到第一个不为要删除的元素时,head不动了,因为最后是要返回它的;这时指定两个指针,pre负责记录上一个不为待删除元素的位置,cur往后移,当cur的值为待删除元素时,就让pre.next = cur.next,就是跳过这个值,而当cur的值不需要删除时,pre = cur,相当于回到了两个指针指向head的时候那样,循环往复,最后把head返回即可。

    public static Node deleteGivenValue(Node head, int value) {
        if (head == null)
            return null;
        while (head.value == value)
            head = head.next;
        Node cur = head;
        Node pre = cur;
        while (cur != null) {
            if (cur.value == value)
                pre.next = cur.next;
            else
                pre = cur;
            cur = cur.next;
        }

        return head;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值