一、随机数的产生
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;
}