List Element
public class ListNode<T> {
T data1;
T data2;
ListNode<T> nextNode;
public ListNode(T data1, T data2) {
this(data1, data2, null);
}
public ListNode(T data1, T data2, ListNode<T> nextNode) {
this.data1 = data1;
this.data2 = data2;
this.nextNode = nextNode;
}
public T getData1() {
return data1;
}
public T getData2() {
return data2;
}
public ListNode<T> getNextNode() {
return nextNode;
}
}
Linked List
public class List<T> {
private ListNode<T> firstNode;
private ListNode<T> lastNode;
private String name;
public List() {
this("list");
}
public List(String name) {
this.name = name;
firstNode = lastNode = null;
}
public void add(T item1, T item2) {
if (isEmpty()) {
firstNode = lastNode = new ListNode<T>(item1, item2);
} else {
lastNode = lastNode.nextNode = new ListNode<T>(item1, item2);
}
}
public boolean isEmpty() {
return firstNode == null;
}
public String toString() {
StringBuilder temp = new StringBuilder();
if (isEmpty()) {
temp.append("Empty " + name);
} else {
ListNode<T> current = firstNode;
while (current != null) {
temp.append(current.data1 + ":" + current.data2);
temp.append(", ");
current = current.nextNode;
}
temp.deleteCharAt(temp.length()-2);
}
return temp.toString();
}
}
public class ListNode<T> {
T data1;
T data2;
ListNode<T> nextNode;
public ListNode(T data1, T data2) {
this(data1, data2, null);
}
public ListNode(T data1, T data2, ListNode<T> nextNode) {
this.data1 = data1;
this.data2 = data2;
this.nextNode = nextNode;
}
public T getData1() {
return data1;
}
public T getData2() {
return data2;
}
public ListNode<T> getNextNode() {
return nextNode;
}
}
Linked List
public class List<T> {
private ListNode<T> firstNode;
private ListNode<T> lastNode;
private String name;
public List() {
this("list");
}
public List(String name) {
this.name = name;
firstNode = lastNode = null;
}
public void add(T item1, T item2) {
if (isEmpty()) {
firstNode = lastNode = new ListNode<T>(item1, item2);
} else {
lastNode = lastNode.nextNode = new ListNode<T>(item1, item2);
}
}
public boolean isEmpty() {
return firstNode == null;
}
public String toString() {
StringBuilder temp = new StringBuilder();
if (isEmpty()) {
temp.append("Empty " + name);
} else {
ListNode<T> current = firstNode;
while (current != null) {
temp.append(current.data1 + ":" + current.data2);
temp.append(", ");
current = current.nextNode;
}
temp.deleteCharAt(temp.length()-2);
}
return temp.toString();
}
}
No comments:
Post a Comment