1. package ChapterFive;
2.
3. class Link<E> {
4.
5. public E data;
6.
7. public Link<E> next;
8.
9. public Link(E data) {
10. this.data = data;
11. }
12. }
13.
14. class LinkList<E> {
15.
16. public Link<E> first;
17. //链表中数据项的个数
18. public int size;
19.
20. public LinkList() {
21. first = null;
22. size = 0;
23. }
24. //在表头插入新的数据
25. public void insertFirst(E value) {
26. Link<E> link = new Link<E>(value);
27. link.next = first;
28. first = link;
29. size++;
30. }
31. //判断链表是否为空
32. public boolean isEmpty() {
33. return size == 0;
34. }
35. //删除表头
36. public Link<E> deleteFirst() {
37. Link<E> temp = first;
38. first = first.next;
39. size--;
40. return temp;
41. }
42. //输出链表中的所有数据
43. public void display() {
44. Link<E> curr = first;
45. while (curr != null) {
46. System.out.print(curr.data + " ");
47. curr = curr.next;
48. }
49. System.out.println();
50. }
51. //返回链表中数据项的个数
52. public int size() {
53. return size;
54. }
55. //获取从头至尾的第i个数据项
56. public Link<E> get(int i) {
57. if (i > size() - 1 || i < 0)
58. try {
59. throw new IndexOutOfBoundsException();
60. } catch (Exception e) {
61. e.printStackTrace();
62. }
63. Link<E> curr = first;
64. for (int n = 0; n < size(); n++) {
65. if (n == i)
66. return curr;
67. else
68. curr = curr.next;
69. }
70. return null;
71. }
72. //输出从头至尾的第i个数据项
73. public void remove(int i) {
74. if (i == 0)
75. deleteFirst();
76. else if (i == size() - 1)
77. get(i - 1).next = null;
78. else {
79. get(i - 1).next = get(i + 1);
80. }
81. size--;
82. }
83. }
84.
85. public class Link_list {
86. public static void main(String[] args) {
87. LinkList<Long> ll = new LinkList<Long>();
88. for (int i = 0; i < 10; i++) {
89. Long value = (long) (Math.random() * 100);
90. ll.insertFirst(value);
91. }
92. ll.display();
93. while (!ll.isEmpty()) {
94. ll.deleteFirst();
95. ll.display();
96. }
97. System.out.println("Ok");
98. }
99. }
|
|