1. package ChapterFive;
2.
3. class SortedLink {
4.
5. public Link<Long> first;
6.
7. int size;
8.
9. public SortedLink() {
10. first = null;
11. size = 0;
12. }
13. //向有序链表中插入数据
14. public void insert(long value) {
15. Link<Long> newLink = new Link<Long>(value);
16. Link<Long> previous = null;
17. Link<Long> curr = first;
18. while (curr != null && (value > curr.data)) {
19. previous = curr;
20. curr = curr.next;
21. }
22. if (previous == null)// 链表为空(在表头插入)
23. first = newLink;
24. else
25. previous.next = newLink;//插入新的节点
26. newLink.next = curr;
27. size++;
28. }
29. //删除第一个节点
30. public Link<Long> remove() {
31. Link<Long> temp = first;
32. first = first.next;
33. size--;
34. return temp;
35. }
36. //判断链表是否为空
37. public boolean isEmpty() {
38. return size == 0;
39. }
40. //输出链表的所有数据
41. public void display() {
42. Link<Long> curr = first;
43. while (curr != null) {
44. System.out.print(curr.data + " ");
45. curr = curr.next;
46. }
47. System.out.println();
48. }
49. }
50.
51. public class SortedLinkApp {
52. public static void main(String[] args) {
53. SortedLink sl = new SortedLink();
54. for (int i = 0; i < 10; i++) {
55. sl.insert((long) (Math.random() * 100));
56. }
57. while (!sl.isEmpty()) {
58. sl.remove();
59. sl.display();
60. }
61. }
62. }
|
|