In: Computer Science
Write a program where you- 1. Create a class to implement "Double Linked List" of integers. (10) 2. Create the list and print the list in forward and reverse directions. (10)
1>
answers
public class DoubleLinkedListImpl<E> {
private Node head;
private Node tail;
private int size;
public DoubleLinkedListImpl() {
size = 0;
}
private class Node {
E element;
Node next;
Node prev;
public Node(E element, Node next, Node prev) {
this.element = element;
this.next = next;
this.prev = prev;
}
}
public int size() { return size; }
public boolean isEmpty() { return size == 0; }
public void addFirstElement(E element) {
Node tmp = new Node(element, head, null);
if(head != null ) {head.prev = tmp;}
head = tmp;
if(tail == null) { tail = tmp;}
size++;
System.out.println("adding: "+element);
}
public void addLastElement(E element) {
Node tmp = new Node(element, null, tail);
if(tail != null) {tail.next = tmp;}
tail = tmp;
if(head == null) { head = tmp;}
size++;
System.out.println("adding: "+element);
}
public void iterateForward(){
System.out.println("iterating forward..");
Node tmp = head;
while(tmp != null){
System.out.println(tmp.element);
tmp = tmp.next;
}
}
public void iterateBackward(){
System.out.println("iterating backword..");
Node tmp = tail;
while(tmp != null){
System.out.println(tmp.element);
tmp = tmp.prev;
}
}
public static void main(String a[]){
DoubleLinkedListImpl<Integer> dll = new
DoubleLinkedListImpl<Integer>();
dll.addFirst(10);
dll.addFirst(34);
dll.addLast(56);
dll.addLast(364);
dll.addFirst(100);
dll.addFirst(340);
dll.addLast(560);
dll.addLast(36);
dll.addFirst(110);
dll.addFirst(304);
dll.iterateForward();
dll.iterateBackward();
}
}
2>answers
import java.util.*;
public class TraverseReverseUsingListIteratorExample {
public static void main(String[] args) {
List aList = new ArrayList();
//Add elements to ArrayList object
aList.add("1");
aList.add("2");
aList.add("3");
aList.add("4");
aList.add("5");
aList.add("6");
aList.add("7");
aList.add("8");
aList.add("9");
aList.add("10");
ListIterator listIterator = aList.listIterator();
System.out.println("Traversing ArrayList in forward direction
using ListIterator");
while(listIterator.hasNext())
System.out.println(listIterator.next());//Print the forward
direction only
System.out.println("Traversing ArrayList in reverse direction
using ListIterator");
while(listIterator.hasPrevious())
System.out.println(listIterator.previous());//backword direction
print the value
}
}
//output
forward direction
1
2
3
4
5
6
7
8
9
10
Traversing ArrayList in reverse direction using ListIterator
10
9
8
7
6
5
4
3
2
1
*/