Implementing stack using linked lists - java

What's the best way to implement a stack using linked lists in Java?
EDIT: I would define best as most efficient using clean code. I have already used an array to implement a stack, but am not familiar with link lists so was wondering if anyone could help me implement something similar to below:
public class StackArray{
private Object [] objArray;
private int stackSize;
public StackArray(){
objArray = new Object[50];
stackSize = 0;
}
public StackArray(int size){
objArray = new Object[size];
stackSize = 0;
}
//public interface methods - push, pop, top, empty & clear
public void push(Object o)throws StackArrayException{
if(stackSize < objArray.length){
objArray[stackSize] = o;
stackSize ++;
}else{
throw new StackArrayException("Stack Overflow");
}
}
public Object pop()throws StackArrayException{
if(stackSize != 0){
stackSize--;
return(objArray[stackSize]);
}else{
throw new StackArrayException("Stack Underflow");
}
}
public void top() throws StackArrayException{
if(stackSize != 0){
return(objArray[stackSize-1]);
}else{
throw new StackArrayException("Stack Underflow");
}
}
public boolean empty(){
return (stackSize == 0):
}
public void clear(){
stackSize = 0;
}
}
EDIT: Here is the linked list implementation if anyone is interested..
public class StackList{
private Node listHead;
protected class Node{
protected Object datum;
protected Node next;
public Node(Object o, Node n){
datum = o;
next = n;
}
public StackList(){
listHead = null;
}
//public interface methods - push pop top empty clear
public void push(Object o){
listHead = new Node(o, listHead);
}
public Object pop() throws StackListException{
if(listHead!=null){
Object top = listHead.datum;
listHead = listHead.next;
return top;
}else{
throw new StackListException("Stack Underflow");
}
}
public Object top()throws StackListException{
if(listHead != null){
return(listHead.datum);
}else{
throw new StackListException("Stack Underflow");
}
}
public boolean empty(){
return (listHead == null);
}
public void clear(){
listHead = null;
}
}

Assuming you genuinely want to do this from scratch rather than using one of the perfectly good existing stack implementations then I would recommend:
Create a "MyStack< T >" class which implements any interfaces you want (perhaps List < T >?)
Within MyStack create a "private static final class Node< T >" inner class for each linked list item. Each node contains a reference to an object of type T and a reference to a "next" Node.
Add a "topOfStack" Node reference to MyStack.
The push and pop operations just need to operate on this topOfStack Node. If it is null, the Stack is empty. I'd suggest using the same method signatures and semantics as the standard Java stack, to avoid later confusion.....
Finally implement any other methods you need. For bonus points, implement "Iterable< T >" in such a way that it remembers the immutable state of the stack at the moment the iterator is created without any extra storage allocations (this is possible :-) )

Why don't you just use the Stack implementation already there?
Or better (because it really a linked list, its fast, and its thread safe): LinkedBlockingDeque

If you're talking about a single linked list (a node has a reference to the next object, but not the previous one), then the class would look something like this :
public class LinkedListStack {
private LinkedListNode first = null;
private LinkedListNode last = null;
private int length = 0;
public LinkedListStack() {}
public LinkedListStack(LinkedListNode firstAndOnlyNode) {
this.first = firstAndOnlyNode;
this.last = firstAndOnlyNode;
this.length++;
}
public int getLength() {
return this.length;
}
public void addFirst(LinkedListNode aNode) {
aNode.setNext(this.first);
this.first = aNode;
}
}
public class LinkedListNode {
private Object content = null;
private LinkedListNote next = null;
public LinkedListNode(Object content) {
this.content = content;
}
public void setNext(LinkedListNode next) {
this.next = next;
}
public LinkedListNode getNext() {
return this.next;
}
public void setContent(Object content) {
this.content = content;
}
public Object getContent() {
return this.content;
}
}
Of course you will need to code the rest of the methods for it to work properly and effectively, but you've got the basics.
Hope this helps!

For implementing stack using using LinkedList- This StackLinkedList class internally maintains LinkedList reference.
StackLinkedList‘s push method internally calls linkedList’s insertFirst() method
public void push(int value){
linkedList.insertFirst(value);
}
StackLinkedList’s method internally calls linkedList’s deleteFirst() method
public void pop() throws StackEmptyException {
try{
linkedList.deleteFirst();
}catch(LinkedListEmptyException llee){
throw new StackEmptyException();
}
}
Full Program
/**
*Exception to indicate that LinkedList is empty.
*/
class LinkedListEmptyException extends RuntimeException{
public LinkedListEmptyException(){
super();
}
public LinkedListEmptyException(String message){
super(message);
}
}
/**
*Exception to indicate that Stack is empty.
*/
class StackEmptyException extends RuntimeException {
public StackEmptyException(){
super();
}
public StackEmptyException(String message){
super(message);
}
}
/**
*Node class, which holds data and contains next which points to next Node.
*/
class Node {
public int data; // data in Node.
public Node next; // points to next Node in list.
/**
* Constructor
*/
public Node(int data){
this.data = data;
}
/**
* Display Node's data
*/
public void displayNode() {
System.out.print( data + " ");
}
}
/**
* LinkedList class
*/
class LinkedList {
private Node first; // ref to first link on list
/**
* LinkedList constructor
*/
public LinkedList(){
first = null;
}
/**
* Insert New Node at first position
*/
public void insertFirst(int data) {
Node newNode = new Node(data); //Creation of New Node.
newNode.next = first; //newLink ---> old first
first = newNode; //first ---> newNode
}
/**
* Deletes first Node
*/
public Node deleteFirst()
{
if(first==null){ //means LinkedList in empty, throw exception.
throw new LinkedListEmptyException("LinkedList doesn't contain any Nodes.");
}
Node tempNode = first; // save reference to first Node in tempNode- so that we could return saved reference.
first = first.next; // delete first Node (make first point to second node)
return tempNode; // return tempNode (i.e. deleted Node)
}
/**
* Display LinkedList
*/
public void displayLinkedList() {
Node tempDisplay = first; // start at the beginning of linkedList
while (tempDisplay != null){ // Executes until we don't find end of list.
tempDisplay.displayNode();
tempDisplay = tempDisplay.next; // move to next Node
}
System.out.println();
}
}
/**
* For implementing stack using using LinkedList- This StackLinkedList class internally maintains LinkedList reference.
*/
class StackLinkedList{
LinkedList linkedList = new LinkedList(); // creation of Linked List
/**
* Push items in stack, it will put items on top of Stack.
*/
public void push(int value){
linkedList.insertFirst(value);
}
/**
* Pop items in stack, it will remove items from top of Stack.
*/
public void pop() throws StackEmptyException {
try{
linkedList.deleteFirst();
}catch(LinkedListEmptyException llee){
throw new StackEmptyException();
}
}
/**
* Display stack.
*/
public void displayStack() {
System.out.print("Displaying Stack > Top to Bottom : ");
linkedList.displayLinkedList();
}
}
/**
* Main class - To test LinkedList.
*/
public class StackLinkedListApp {
public static void main(String[] args) {
StackLinkedList stackLinkedList=new StackLinkedList();
stackLinkedList.push(39); //push node.
stackLinkedList.push(71); //push node.
stackLinkedList.push(11); //push node.
stackLinkedList.push(76); //push node.
stackLinkedList.displayStack(); // display LinkedList
stackLinkedList.pop(); //pop Node
stackLinkedList.pop(); //pop Node
stackLinkedList.displayStack(); //Again display LinkedList
}
}
OUTPUT
Displaying Stack > Top to Bottom : 76 11 71 39
Displaying Stack > Top to Bottom : 71 39
Courtesy : http://www.javamadesoeasy.com/2015/02/implement-stack-using-linked-list.html

Use the STL adapter std::stack. Why? Because the code you don't have to write is the fastest way to completion of your task. stack is well-tested, and likely to not need any attention from you. Why not? Because there are some special-purpose requirements needed by your code, undocumented here.
By default stack uses a deque double-ended queue, but it merely requires the underlying container to support "Back Insertion Sequence", also known as .push_back.
typedef std::stack< myType, std::list<myType> > myStackOfTypes;

Here is a tutorial implement using an array and linked list stack implementation.
It depends on the situation.
Array :- you can not resize it (fix size)
LinkedList :- it takes more memory than the array-based one because it wants to keep next node in memory.

I saw many stack implementation using LinkedList, At the end I understand what stack is.. and implemented stack by myself(for me it's clean and efficient). I hope you welcome new implementations. Here the code follows.
class Node
{
int data;
Node top;
public Node()
{
}
private Node(int data, Node top)
{
this.data = data;
this.top = top;
}
public boolean isEmpty()
{
return (top == null);
}
public boolean push(int data)
{
top = new Node(data, top);
return true;
}
public int pop()
{
if (top == null)
{
System.out.print("Stack underflow<-->");
return -1;
}
int e = top.data;
top = top.top;
return e;
}
}
And here the main class for it.
public class StackLinkedList
{
public static void main(String[] args)
{
Node stack = new Node();
System.out.println(stack.isEmpty());
stack.push(10);
stack.push(20);
stack.push(30);
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.isEmpty());
System.out.println(stack.pop());
System.out.println(stack.isEmpty());
System.out.println(stack.pop());
}
}

Related

Make an int search(Object o) method for a stack that uses nodes

I'm trying to make a generic stack and queue class that uses the generic node class. It has empty(), pop(), peek(), push(), and a search() method. I know there is a built-in Stack class and stack search method but we have to make it by using the Node class.
I am unsure of how to make the search method. The search method is supposed to return the distance from the top of the stack of the occurrence that is nearest the top of the stack. The topmost item is considered to be at distance 1; the next item is at distance 2; etc.
My classes are below:
import java.io.*;
import java.util.*;
public class MyStack<E> implements StackInterface<E>
{
private Node<E> head;
private int nodeCount;
public static void main(String args[]) {
}
public E peek() {
return this.head.getData();
}
public E pop() {
E item;
item = head.getData();
head = head.getNext();
nodeCount--;
return item;
}
public boolean empty() {
if (head==null) {
return true;
} else {
return false;
}
}
public void push(E data) {
Node<E> head = new Node<E>(data);
nodeCount++;
}
public int search(Object o) {
// todo
}
}
public class Node<E>
{
E data;
Node<E> next;
// getters and setters
public Node(E data)
{
this.data = data;
this.next = null;
}
public E getData() {
return data;
}
public void setData(E data) {
this.data = data;
}
public Node<E> getNext() {
return next;
}
public void setNext(Node<E> next) {
this.next = next;
}
}
public class MyQueue<E> implements QueueInterface<E>
{
private Node<E> head;
private int nodeCount;
Node<E> rear;
public MyQueue()
{
this.head = this.rear = null;
}
public void add(E item){
Node<E> temp = new Node<E>(item);
if (this.rear == null) {
this.head = this.rear = temp;
return;
}
this.rear.next = temp;
this.rear = temp;
}
public E peek(){
return this.head.getData();
}
public E remove(){
E element = head.getData();
Node<E> temp = this.head;
this.head = this.head.getNext();
nodeCount--;
return element;
}
}
After working on it based off of the first comment I have this:
public int search(Object o){
int count=0;
Node<E> current = new Node<E> (head.getData());
while(current.getData() != o){
current.getNext();
count++;
}
return count;
}
It doesn't have any errors but I cannot tell if it is actually working correctly. Does this seem correct?
It needs the following improvements,
search method should have parameter of type 'E'. So, the signature should look like public int search(E element)
start the count with 1 instead of 0.As you have mentioned topmost item is considered to be at distance 1
initialize current with head, because creating a new node with data value of head(new node(head.getData())) will create an independent node with data same as head node; and the while will run only for the head node as current.getNext() will be null always. Node<E> current = head will create another reference variable pointing to the head.
Instead of != in condition, use if( !current.getData().equals(element.getData())) )
If using your own class as data type, don't forget to override equals method.
Change current.getNext(); to current = current.getNext();
You have problems with other method. Pay attention on top == null. To calculate search() all you need is just iterate over the elements and find position of required value:
public class MyStack<E> {
private Node<E> top;
private int size;
public void push(E val) {
Node<E> node = new Node<>(val);
node.next = top;
top = node;
size++;
}
public E element() {
return top == null ? null : top.val;
}
public E pop() {
if (top == null)
return null;
E val = top.val;
top = top.next;
size--;
return val;
}
public boolean empty() {
return size == 0;
}
public int search(E val) {
int res = 1;
Node<E> node = top;
while (node != null && node.val != val) {
node = node.next;
res++;
}
return node == null ? -1 : res;
}
private static final class Node<E> {
private final E val;
private Node<E> next;
public Node(E val) {
this.val = val;
}
}
}
I assume your MyStack class should be compatible with the Stack class provided by Java as you mention it in your question. This means that your signature public int search(Object o) matches the signature of java.util.Stack#search (apart from synchronised).
To implement the search method using your Node class, we need to traverse the stack and return the index of the first (uppermost) match. First, assign head to a local variable (current). Then you can create a loop where you current.getNext() at the end to get the next element. Stop if the next element is null as we have reached the end of the stack. In the loop, you either count up the index or return this index when the current element's data matches the argument o.
The evaluation needs to be able to deal with null values for your argument o. Therefore, you need to check for null first and adjust your logic accordingly. When o is null, do a null-check against current.getData(). If o is not null, check if current.getData() is equal to o with equals().
Here is a working example: (compatible with java.util.Stack#search)
public int search(Object o) {
int index = 1;
Node<E> current = head;
while (current != null) {
if (o == null) {
if (current.getData() == null) {
return index;
}
} else {
if (o.equals(current.getData())) {
return index;
}
}
current = current.getNext();
index++;
}
return -1; // nothing found
}
To test this, you can write a simple unit test with JUnit like this:
#Test
public void testMyStackSearch() {
// initialize
final MyStack<String> stack = new MyStack<>();
stack.push("e5");
stack.push("e4");
stack.push(null);
stack.push("e2");
stack.push("e1");
// test (explicitly creating a new String instance)
assertEquals(5, stack.search(new String("e5")));
assertEquals(3, stack.search(null));
assertEquals(2, stack.search(new String("e2")));
assertEquals(1, stack.search(new String("e1")));
assertEquals(-1, stack.search("X"));
}
Since you have already a reference implementation, you can replace MyStack with Stack (java.util.Stack) and see if your asserts are correct. If this runs successfully, change it back to MyStack and see if your implementation is correct.
Note: I do not recommend to actually use the Stack implementation in Java. Here, it just serves as a reference implementation for the java.util.Stack#search method. The Deque interface and its implementations offer a more complete and consistent set of LIFO stack operations, which should be used in preference to Stack.

Use a constructor to copy a Stack

Recently,I'm learing the Algorithms 4th,when I come to solve the problem that
Create a new constructor for the linked-list implementation of Stack.java so that Stack t = new Stack(s) makes t reference a new and independent copy of the stack s.
Here is the Stack.java
import java.util.Iterator;
import java.util.NoSuchElementException;
public class Stack<Item> implements Iterable<Item> {
private Node<Item> first; // top of stack
private int n; // size of the stack
private static class Node<Item> {
private Item item;
private Node<Item> next;
}
/**
* Initializes an empty stack.
*/
public Stack() {
first = null;
n = 0;
}
public boolean isEmpty() {
return first == null;
}
public int size() {
return n;
}
public void push(Item item) {
Node<Item> oldfirst = first;
first = new Node<Item>();
first.item = item;
first.next = oldfirst;
n++;
}
public Item pop() {
if (isEmpty()) throw new NoSuchElementException("Stack underflow");
Item item = first.item; // save item to return
first = first.next; // delete first node
n--;
return item; // return the saved item
}
private class ListIterator<Item> implements Iterator<Item> {
private Node<Item> current;
public ListIterator(Node<Item> first) {
current = first;
}
public boolean hasNext() {
return current != null;
}
public void remove() {
throw new UnsupportedOperationException();
}
public Item next() {
if (!hasNext()) throw new NoSuchElementException();
Item item = current.item;
current = current.next;
return item;
}
}
The answer of Recursive solution is that create a copy constructor for a linked list starting at a given Node and use this to create the new stack.
Node(Node x) {
item = x.item;
if (x.next != null) next = new Node(x.next);
}
public Stack(Stack<Item> s) { first = new Node(s.first); }
But what make me confused is how can I combine the above code to the Stack.java as its constuctor,how can I handle the Node? to create a new class Node??May someone could hep me:)
You don't need to create a new class Node. The Node is the same for the old stack and the new stack 't'.
Currently you have one constructor in your Stack class public Stack(). You need to make another one that accepts a Stack, as you've done in your example, which then calls a method that copies the old elements to the new stack (recursively or iteratively). It sounds like homework so I don't think any code is appropriate (not sure of the rules in that regard).
Here is the code fragment I hava solved my problem
private class Node{
Item item;
Node next;
Node() { } //default constructor Node
Node(Node x){
item=x.item;
if(x.next!=null) next=new Node(x.next);
}
}
public Stack(){ //default constructor Stack
first=null;
N=0;
}
public Stack(Stack<Item> s) {first=new Node(s.first); }

What does it mean to return an iterator? Java

I have to write a class that implements the Iterable interface. I'm confused about what it means to return an iterator object. An iterator just goes through the elements of a list, so how would I return this as an object? Would I return a list that was able to be iterated through or what? How can an iterator be an object when all it does is go through or change data in other objects?
Here is an example of a very simplistic list. It represents the list as linked elements.
The iterator object is created as an anonymous inner class holding the current element as the state. Each call of iterator() creates a new iterator object.
import java.util.Iterator;
public class SimplisticList<T> implements Iterable<T> {
/*
* A list element encapsulates a data value and a reference to the next
* element.
*/
private static class Element<T> {
private T data;
private Element<T> next;
Element(T data) {
this.data = data;
next = null;
}
public T getData() {
return data;
}
public Element<T> getNext() {
return next;
}
public void setNext(Element<T> next) {
this.next = next;
}
}
// We only need a reference to the head of the list.
private Element<T> first = null;
// The list is empty if there is no first element.
public boolean isEmpty() {
return first == null;
}
// Adding a new list element.
// For an empty list we only have to set the head.
// Otherwise we have to find the last element to add the new element.
public void add(T data) {
if(isEmpty()) {
first = new Element<T>(data);
} else {
Element<T> current = first;
while(current.getNext() != null) {
current = current.getNext();
}
current.setNext(new Element<T>(data));
}
}
#Override
public Iterator<T> iterator() {
// Create an anonymous implementation of Iterator<T>.
// We need to store the current list element and initialize it with the
// head of the list.
// We don't implement the remove() method here.
return new Iterator<T>() {
private Element<T> current = first;
#Override
public boolean hasNext() {
return current != null;
}
#Override
public T next() {
T result = null;
if(current != null) {
result = current.getData();
current = current.getNext();
}
return result;
}
#Override
public void remove() {
// To be done ...
throw new UnsupportedOperationException();
}
};
}
}
Returing an iterator means returning an instance of a class that implements the Iterator interface. This class has to implement hasNext(),next() and remove(). The constructor of the class should initialize the instance in a way that next() would return the first element of the data structure you are iterating over (if it's not empty).
Here's a simple example of an iterator that goes through an String[] array:
public class MyIterator implements Iterator<String> {
private String[] arr;
private int index;
public MyIterator(String[] arr) {
this.arr = arr;
this.index = 0;
}
public boolean hasNext() {
return index < arr.length;
}
public String next() {
return arr[index++];
}
}
(You also need remove() but that would just throw an exception.) Note that when you construct one of these iterators with new MyIterator(myStringArray), you construct an object that has a reference to the array. The Iterator wouldn't be the array itself, or any part of it, but it has a private variable that refers to it. An Iterator for a list or for any other data structure (or even for things that aren't data structures) would follow a similar pattern.

Implementation of ArrayList using a LinkedList

I need to implement both a Queue and ArrayList by using an internal LinkedList. I created my DoublyLinkedList class and was able to implement it into my queue with no problem. The problem I am running into is that to add or delete to/from the ArrayList, the add/delete methods take in a integer for the index and an object/element. All my methods inside my DoublyLinkedList class take in either elements and/or Nodes.
My question is this, how can I implement my DoublyLinkedList methods inside my ArrayList when my DLL class doesn't take any int values in.
I want to be able to add or delete the node by using the index, but I can't. Realistically, I would want something like list.addAfter(I) without I being an integer.
Note: The goal of this assignment is to implement ADTs, so I can't modify the method signatures of the ArrayList ADT.
DoublyLinedList Class
public class DoublyLinkedList<E> {
private Node<E> head;
private Node<E> tail;
private int size;
public DoublyLinkedList() {
this.head = new Node<E>(null, null, null);
this.tail = new Node<E>(null, null, null);
this.size = 0;
head.setNext(tail);
tail.setPrev(head);
}
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public Node<E> getPrev(Node<E> n) {
return n.getPrev();
}
public Node<E> getNext(Node<E> n) {
return n.getNext();
}
public Node<E> getFirst() {
return head.getNext();
}
public Node<E> getLast() {
return tail.getPrev();
}
public E remove(Node<E> c) {
Node<E> a = c.getPrev();
Node<E> b = c.getNext();
b.setNext(a);
a.setPrev(b);
c.setNext(null);
c.setPrev(null);
size--;
return c.getElement();
}
public E removeFirst() {
return remove(head.getNext()); // first element is beyond header
}
public E removeLast() {
return remove(tail.getPrev());
}
public void addBefore(Node<E> node, E e) {
Node<E> prev = getPrev(node);
Node<E> n = new Node<E>(e, prev, node);
node.setPrev(n);
prev.setNext(n);
size++;
}
public void addFirst(E e) {
addAfter(head, e);
}
public void addLast(E e) {
addBefore(tail, e);
}
public void addAfter(Node<E> node, E e) {
Node<E> next = getNext(node);
Node<E> n = new Node<E>(e, node, next);
node.setNext(n);
next.setPrev(n);
size++;
}
}
LArrayList class (my Arraylist implementation)
public class LArrayList implements List {
private DoublyLinkedList list;
private int size;
public LArrayList() {
this.list = new DoublyLinkedList();
this.size = 0;
}
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public void add(int I, Object e) throws IndexOutOfBoundsException {
if (isEmpty()) {
list.addFirst(e);
}
// HERE IS MY CONCERN. THESE FOUR METHODS ALL TAKE IN INT VALUES WHILE
// NON OF MY DLL METHODS DO!
}
public Object get(int i) throws IndexOutOfBoundsException {
return null;
}
public Object remove(int i) throws IndexOutOfBoundsException {
return null;
}
public Object set(int I, Object e) throws IndexOutOfBoundsException {
return null;
}
}
It seems like a fairly easy thing to do - just use the API exposed by your LinkedList and add some logic to it. Here is the bit you are missing
if (list.size() < I) {
throw new IndexOutOfBoundsException()
}
//get a starting point
Node node = list.getFirst();
//loop until you get to the specified position
while(I-- > 0) {
node = list.getNext(node);
}
//now node points at the node in position I - insert the new
//node before it to comply with the List interface
list.addBefore(node, e);
this.size++;
I do have to note that your LinkedList implementation can be improved - first of all, the getPrev() getNext() addBefore() and addAfter() should be static, as you shouldn't have to use a LinkedList instance to call them. However, it would be even better if the methods were actually methods in Node, because that way the traversal and usage of the LinkedList would be way more easy. Here is how the above code would look like if the methods were in Node:
if (list.size() < I) {
throw new IndexOutOfBoundsException()
}
//get a starting point
Node node = list.getFirst();
//loop until you get to the specified position
while(I-- > 0) {
node = node.getNext();
}
//now node points at the node in position I - insert the new
//node before it to comply with the List interface
node.addBefore(e);
this.size++;
You pretty much do not need the list at all - certainly you don't need to just pass extra parameters to some functions. You can still keep the (hopefully static) methods in Linked list that do the same thing, but they'd just be proxies for the Node implementation of the methods, e.g.:
public static void addAfter(Node<E> node, E e) {
node.addAfter(e);
}
I am not sure if you will need these methods in LinkedList but they can certainly be there for "backwards compliance", if you will.
EDIT Forgot to mention - the fist bit of code is the implementation for add(), I am sure you can work out the rest, as they'd do the same thing.
public Object get(int i) throws IndexOutOfBoundsException {
if(list.size()<=i) throw new IndexOutOfBoundsException();
Node current = list.getFirst();
for(int x = 0; x<=i; x++){
if(x == i) return current.getElement();//Change this behaviour for remove and set
current = current.getNext();
}
}

Doubly linked lists

I have an assignment that I am terribly lost on involving doubly linked lists (note, we are supposed to create it from scratch, not using built-in API's). The program is supposed to keep track of credit cards basically. My professor wants us to use doubly-linked lists to accomplish this. The problem is, the book does not go into detail on the subject (doesn't even show pseudo code involving doubly linked lists), it merely describes what a doubly linked list is and then talks with pictures and no code in a small paragraph. But anyway, I'm done complaining. I understand perfectly well how to create a node class and how it works. The problem is how do I use the nodes to create the list? Here is what I have so far.
public class CardInfo
{
private String name;
private String cardVendor;
private String dateOpened;
private double lastBalance;
private int accountStatus;
private final int MAX_NAME_LENGTH = 25;
private final int MAX_VENDOR_LENGTH = 15;
CardInfo()
{
}
CardInfo(String n, String v, String d, double b, int s)
{
setName(n);
setCardVendor(v);
setDateOpened(d);
setLastBalance(b);
setAccountStatus(s);
}
public String getName()
{
return name;
}
public String getCardVendor()
{
return cardVendor;
}
public String getDateOpened()
{
return dateOpened;
}
public double getLastBalance()
{
return lastBalance;
}
public int getAccountStatus()
{
return accountStatus;
}
public void setName(String n)
{
if (n.length() > MAX_NAME_LENGTH)
throw new IllegalArgumentException("Too Many Characters");
else
name = n;
}
public void setCardVendor(String v)
{
if (v.length() > MAX_VENDOR_LENGTH)
throw new IllegalArgumentException("Too Many Characters");
else
cardVendor = v;
}
public void setDateOpened(String d)
{
dateOpened = d;
}
public void setLastBalance(double b)
{
lastBalance = b;
}
public void setAccountStatus(int s)
{
accountStatus = s;
}
public String toString()
{
return String.format("%-25s %-15s $%-s %-s %-s",
name, cardVendor, lastBalance, dateOpened, accountStatus);
}
}
public class CardInfoNode
{
CardInfo thisCard;
CardInfoNode next;
CardInfoNode prev;
CardInfoNode()
{
}
public void setCardInfo(CardInfo info)
{
thisCard.setName(info.getName());
thisCard.setCardVendor(info.getCardVendor());
thisCard.setLastBalance(info.getLastBalance());
thisCard.setDateOpened(info.getDateOpened());
thisCard.setAccountStatus(info.getAccountStatus());
}
public CardInfo getInfo()
{
return thisCard;
}
public void setNext(CardInfoNode node)
{
next = node;
}
public void setPrev(CardInfoNode node)
{
prev = node;
}
public CardInfoNode getNext()
{
return next;
}
public CardInfoNode getPrev()
{
return prev;
}
}
public class CardList
{
CardInfoNode head;
CardInfoNode current;
CardInfoNode tail;
CardList()
{
head = current = tail = null;
}
public void insertCardInfo(CardInfo info)
{
if(head == null)
{
head = new CardInfoNode();
head.setCardInfo(info);
head.setNext(tail);
tail.setPrev(node) // here lies the problem. tail must be set to something
// to make it doubly-linked. but tail is null since it's
// and end point of the list.
}
}
}
Here is the assignment itself if it helps to clarify what is required and more importantly, the parts I'm not understanding. Thanks
https://docs.google.com/open?id=0B3vVwsO0eQRaQlRSZG95eXlPcVE
if(head == null)
{
head = new CardInfoNode();
head.setCardInfo(info);
head.setNext(tail);
tail.setPrev(node) // here lies the problem. tail must be set to something
// to make it doubly-linked. but tail is null since it's
// and end point of the list.
}
the above code is for when u not have any nodes in list, here u r going to add nodes to ur list.I.e. ist node to list
here u r pointing head & tail to same node
I assume CardList is meant to encapsulate the actual doubly-linked-list implementation.
Consider the base case of a DLL with only a single node: the node's prev and next references will be null (or itself). The list's encapsulation's head and tail references will both be the single node (as the node is both the start and end of the list). What's so difficult to understand about that?
NB: Assuming that CardList is an encapsulation of the DLL structure (rather than an operation) there's no reason for it to have a CardInfoNode current field, as that kind of state information is only useful to algorithms that work on the structure, which would be maintaining that themselves (it also makes your class thread-unsafe).

Categories