Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Program1 1 – Generic Linked List
- public class GenericProject {
- public static void main(String[] args) {
- }
- }
- abstract class GenericList<I> {
- Node<I> head;
- private int length;
- // abstract prototye that will be overridden by the GenericQueue and GenericStack class
- public abstract void add(I data);
- // prints list items, one per line
- public void print() {
- if (head == null) {
- System.out.println("The list is empty.");
- return;
- }
- Node<I> n = head;
- while (n!=null) {
- System.out.println(n.data);
- n = n.next;
- }
- }
- // returns the first value in the list and deletes the node
- public I delete() {
- if (head == null) { // if the list is empty, nothing needs to be deleted
- return null;
- }
- I contents = head.data; // save the contents of the first node
- head = head.next; // move the head, deleting the node
- setLength(getLength()-1);
- return contents;
- }
- // gets the current length of the list
- public int getLength() { return length; }
- // sets the current length of the list
- public void setLength(int len) { length = len; }
- // node class for individual list items
- class Node<T> {
- T data;
- Node next;
- Node(T data) {
- this.data = data;
- setLength(getLength()+1);
- }
- }
- }
- class GenericQueue<I> extends GenericList<I> { // FIFO
- // constructor that takes a parameter to initialize the head
- GenericQueue(I data) {
- head = new Node<I>(data);
- }
- // overrides add() in GenericList. the enqueue operation is implemented
- public void add(I data) {
- Node<I> n = new Node(data); // create a new node
- if (head == null) { // empty list case
- head = n;
- }
- else {
- Node<I> t = head;
- while (t.next != null) {
- t = t.next;
- }
- t.next = n;
- }
- }
- // calls add() with enqueue implemented
- public void enqueue(I data) {
- add(data);
- }
- // calls delete() with dequeue implemented
- public I dequeue() {
- return delete();
- }
- }
- class GenericStack<I> extends GenericList<I> { // LIFO
- // constructor that takes a parameter to initialize the head
- GenericStack(I data) {
- head = new Node(data);
- }
- // overrides add() in GenericList. the push operation is implemented
- public void add(I data) {
- Node<I> t = head;
- head = new Node(data);
- head.next = t;
- }
- // calls add() with push implemented
- public void push(I data) {
- add(data);
- }
- // calls delete with pop implemented
- public I pop() {
- return delete();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement