class Link {
public int iData;
public Link next;
public Link previous;
public Link(int id) {
iData = id;
}
public String toString() {
return "{" + iData + "} ";
}
}
class LinkList {
private Link first;
public LinkList() {
first = null;
}
public Link getFirst() {
return first;
}
public void setFirst(Link f) {
first = f;
}
public boolean isEmpty() {
return first == null;
}
public ListIterator getIterator() {
return new ListIterator(this);
}
public String toString() {
Link current = first;
String str ="";
while (current != null) {
str += current.toString();
current = current.next;
}
return str;
}
}
class ListIterator {
private Link current;
private Link previous;
private LinkList ourList;
public ListIterator(LinkList list) {
ourList = list;
reset();
}
public void reset() {
current = ourList.getFirst();
previous = null;
}
public boolean atEnd() {
return (current.next == null);
}
public void nextLink() {
previous = current;
current = current.next;
}
public Link getCurrent() {
return current;
}
public void insertAfter(int dd) {
Link newLink = new Link(dd);
if (ourList.isEmpty()) {
ourList.setFirst(newLink);
current = newLink;
} else {
newLink.next = current.next;
current.next = newLink;
nextLink();
}
}
public void insertBefore(int dd) {
Link newLink = new Link(dd);
if (previous == null) {
newLink.next = ourList.getFirst();
ourList.setFirst(newLink);
reset();
} else {
newLink.next = previous.next;
previous.next = newLink;
current = newLink;
}
}
public double deleteCurrent() {
int value = current.iData;
if (previous == null) {
ourList.setFirst(current.next);
reset();
} else {
previous.next = current.next;
if (atEnd())
reset();
else
current = current.next;
}
return value;
}
}
public class MainClass {
public static void main(String[] args) {
LinkList theList = new LinkList();
ListIterator iter1 = theList.getIterator();
iter1.insertAfter(20);
iter1.insertAfter(40);
iter1.insertAfter(80);
iter1.insertBefore(60);
System.out.println(theList);
iter1.reset();
if (!theList.isEmpty() && !iter1.atEnd()){
iter1.nextLink();
}
System.out.println("Returned " + iter1.getCurrent().iData);
iter1.insertBefore(99);
iter1.insertAfter(100);
System.out.println(theList);
}
}
|