Java Reference
In-Depth Information
If you combine the toString method and the add method, along with a construc-
tor that initializes the front of the list to null , you end up with the following first ver-
sion of the LinkedIntList class:
1 // Simple first version of LinkedIntList with just a constructor
2 // and methods for add and toString.
3
4 public class LinkedIntList {
5
private ListNode front; // first value in the list
6
7 // post: constructs an empty list
8 public LinkedIntList() {
9 front = null;
10 }
11
12 // post: returns comma-separated, bracketed version of list
13 public String toString() {
14 if (front == null) {
15 return "[]";
16 } else {
17 String result = "[" + front.data;
18 ListNode current = front.next;
19 while (current != null) {
20 result += ", " + current.data;
21 current = current.next;
22 }
23 result += "]";
24 return result;
25 }
26 }
27
28 // post: appends the given value to the end of the list
29 public void add( int value) {
30 if (front == null) {
31 front = new ListNode(value);
32 } else {
33 ListNode current = front;
34 while (current.next != null) {
35 current = current.next;
36 }
37 current.next = new ListNode(value);
38 }
39 }
40 }
 
Search WWH ::




Custom Search