-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRandomNumberList.java
More file actions
99 lines (82 loc) · 2.23 KB
/
RandomNumberList.java
File metadata and controls
99 lines (82 loc) · 2.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
//******************************************************************************
// Filename: RandomNumberList.java
//
// Author: David C. Drake (https://davidcdrake.com)
//
// Description: RandomNumberList, NumberList, and RandomNumber classes for
// generating, printing, and recursively sorting linked lists of
// random numbers.
//******************************************************************************
import java.util.*;
public class RandomNumberList {
public static void main(String[] args) {
final int LIST_SIZE = 50;
NumberList numList = new NumberList();
for (int x = 0; x < LIST_SIZE; x++) {
numList.insert(new RandomNumber());
}
for (int x = 0; x < LIST_SIZE; x++) {
numList.sort(numList.list);
}
System.out.println(numList);
}
}
class NumberList {
public NumberNode list;
NumberList() {
list = null;
}
public void insert(RandomNumber newNumber) {
NumberNode node = new NumberNode(newNumber);
NumberNode current;
if (list == null) {
list = node;
} else {
current = list;
while (current.next != null) {
current = current.next;
}
current.next = node;
}
}
public void sort(NumberNode currentNode) { // Sorts in descending order.
int temp1, temp2;
if (currentNode.next != null) {
temp1 = currentNode.num.value;
temp2 = currentNode.next.num.value;
if (temp1 < temp2) {
currentNode.num.value = temp2;
currentNode.next.num.value = temp1;
}
sort(currentNode.next);
}
}
public String toString() {
String result = "";
NumberNode current = list;
while (current != null) {
result += current.num.toString() + "\n";
current = current.next;
}
return result;
}
private class NumberNode {
public RandomNumber num;
public NumberNode next;
public NumberNode(RandomNumber theNumber) {
num = theNumber;
next = null;
}
}
}
class RandomNumber {
final int MAX_ABS_VALUE = 100;
Random r = new Random();
public int value;
public RandomNumber() {
value = (int) ((Math.random() * (2 * MAX_ABS_VALUE)) - MAX_ABS_VALUE);
}
public String toString() {
return ("" + value);
}
}