Problem with methods of a doubly linked list - java

I have been trying to create (I have been learning it) a doubly linked list based on an exercise, in which the list will be train with wagons. The exercise asks to create a class "wagon" with the attributes "name of wagon", "next wagon" and "previous wagon", and another class "train" with the methods to add wagons, print the wagons and sawp the order of the locomotives of the trains. My problem is in how the exercise asks to create the method to add wagons, and the one to swap the order of the locomotives. The method to add wagons has a parameter that has as data type the class "wagon", and I have really not gotten to create this method. I am going to show you what I have already done in the code below. Could anyone help me with that? I have not understood how to use the parameter "vagaoCriar" in the method.
Besides that, the exercise asks to create two trains (then two lists), and to change the two locomotives of the two trains. I would like to know if that is really possible with two doubly linked lists, to swap two elements of them between themselves, or could it be simply swapping the order of the two doubly linked lists, without having to change elements between them? Because I have already searched it enough and I have not found anything saying that it is possible to swap elements between two doubly linked lists. Still, I have had some problem to create the method to swap the locomotives of the train, because the method has as data type "wagon", but it has as parameter "name of wagon" (String), and the name of the method is "get wagon and remove", so I do not have idea what the exercise really wishes.
I understand that the questions is long, but for such a complex example (for me), I could not be concise.
public class Vagao {
String nomeDoVagao;
Wagon vagaoAnterior;
Wagon vagaoPosterior;
public Vagao (String nomeDoVagao){
this.nomeDoVagao = nomeDoVagao;
vagaoAnterior = null;
vagaoPosterior = null;
}
}
public class Trem {
Vagao head, tail = null;
//I do not know to proceed here
public void adicionarVagao (Vagao vagaoCriar){
Vagao novo_Vagao = new Vagao (vagaoCriar.nomeDoVagão);
if (head == null){
head = tail = novo_Vagao;
head.vagaoAnterior = null;
tail.vagaoPosterior = null;
} else {
tail.vagaoPosterior = novo_Vagao;
novo_Vagao.vagaoAnterior = tail;
tail = novo_Vagao;
tail.vagaoPosterior = null;
}
}
//This is the other method, that I have not understood well, so I have not
even begun it
public Vagao pegarVagaoRemover (String nomeDoVagao){...}
}
This is how I have tried to create a "train" and print it in the console, but it has not worked:
public class Main {
public static void main(String[] args) {
Trem trem = new Trem();
trem.adicionarVagao("qualquer");
trem.printTrem();
}
}

head and tail are not indepedant wagons themselves.
So one should not alter head's or tail's fields in general.
Adding at the end:
novo_Vagao.vagaoAnterior = null;
novo_Vagao.vagaoPosterior = null;
if (head == null){
head = tail = novo_Vagao;
} else {
novo_Vagao.vagaoAnterior = tail;
tail.vagaoPosterior = novo_Vago;
tail = novo_Vagao;
}
Removal would go:
if (vagao.vagaoPosterio == null) {
tail = vagao.vagaoAnterior;
} else {
vagao.vagaoPosterio.vagaoAnterio = vagao.vagaoAnterior;
}
...
So: what referencing fields to change.

Related

Circular Linked List Node Insertion Java

I tried implementing the insert method for circular linked list. I think I had some success.
Problem:
When I display the list. The display method will loop because every next variable of the link is linked to a non-null node object. So head will never be a null object. From what I recall about singly linked list, head always point to the first node in the list or the first node with data inside of it.
My conceptual understanding of circular linked list:
From what I can understand circular linked is somewhat like a singly linked list but with a slight twist: the next variable of the tail object points to the head.
I'm coding it like the diagram has presented provided by the source link.
Source: http://sourcecodemania.com/circular-linked-lists/
public void insert(String data)
{
Link link = new Link(data);
if(head == null)
{
head = link;
tail= link;
}
else
{
tail.next = link;
tail = link;
tail.next = head;
}
}
public void display()
{
// good implementation for display #2
while(head != null)
{
// System.out.println (head.data);
head = head.next;
}
}
Once you insert at least one element, you would never come across null. It will keep on going till infinity.
Also, it might not be a good idea to modify head just for displaying the list. Operation like display should not have any side effects.
In stead, keep a member field size in your list class and update it in each insert and delete method.
Now you would know how many times you should iterate the loop.
ListClassName current = head; // Head is not modified.
for (int i = 0; i < this.size; i++) {
// System.out.println (current.data);
current = current.next;
}
Good luck.
You can keep a reference to the first Link object and check to make sure head is not equal to this object while looping:
public void display()
{
boolean first=true;
Link firstItem=null;
// good implementation for display #2
while(head != null && head!= firstItem)
{
if(first){
firstItem=head;
first=false;
}
// System.out.println (head.data);
head = head.next;
}
}

Using Command Design Pattern for just Undo

Okay so this is my first time using really any Design Pattern so forgive me but I'm really struggling with the concept. From what I've read there needs to be the Command interface, usually this would hold public void execute(); In my case I think I want to only have public void undo(); My question is on all the other classes that are required. My program is essentially done and I'm trying to merge this design pattern in at the end to put in a Undo function. It's a LinkedList that i defined with my own methods. Here's some of the code:
public class LinkedList<E> implements Serializable{
/** number of Nodes on the list */
private int count;
/** the first Node in the list */
private Node head;
/** the last Node in the list */
private Node tail;
/**Stack holding commands*/
private Stack<Command> undo = new Stack<Command>();
/** Inserts a given student's data into the database
* #param student given student data to be inserted into database
* #return none*/
public void insert(Student student){
//case where input is null
if(student.getName() == null || student.getGNumber() == null)
throw new IllegalArgumentException();
Node temp = head;
//case where there is no list
if(head == null){
head = new Node(student, null);
tail = head;
count = 1;
}
//case where top has existing Nodes
else{
//brings reference to end of list
while(temp.getNext() != null)
temp = temp.getNext();
temp.setNext(new Node(student, null));
tail = temp;
count ++;
}
}
Now would that be the receiver class? And do I still need a separate class for each command? Really all I want is an Undo Stack of commands, and each time I call a method I push it's undo onto that stack. For all the Command Design Pattern examples I could find they've all been the same example of that Light Switch which really doesn't do a good job showing a generic need.
Okay sorry for being really long winded, I guess here is the TL;DR question:
Can I add a Stack in my LinkedList, and then add a undo method also in the LinkedList that pops the stack? and add a push statement in each of my methods? or do I still need to go through all the steps and classes of the Command Design Pattern?
EDIT:
After some thought I realized to push a command into my Stack I need command objects for each of my methods, is there a way to implement this into my LinkedList class?

How to use Comparable as a Generic parameter in a Class

I have a home work in a data structures course, the question is:
Implementation of doubly-linked list class.
the methods:
display()
length() or size()
insertSorted(Comparable)
insertToEnd(Comparable)
insertToHead(Comparable)
delete(Comparable)
boolean search(Comparable)
You must do this in JAVA
Create an application layer to test your class and its methods.
Compress all of your source files into a file and rename it as CS214HW1_first_lastName.zip Put your name in the filename. If needed, add a ReadMe.txt file for extra information such as compilation.
I implemented everything correctly and the code is working fine, but I used for example: insertSorted(int) instead of insertSorted(Comparable), because I didn't know how to do it.
I searched online, and read the JAVA documentation for (Comparable) but it is not enough :(
Can anybody help, please it is very important?
Here's some of my code, I can't write it all, cuz I don't want my friends to get the same code.
I will take zero if there is same code.
Code:
class DLL {
class Node {
Node next;
Node prev;
int data;
Node() {
next = null;
prev = null;
data = 0;
}
Node(int dt) {
next = null;
prev = null;
data = dt;
}
}
Node head;
void insertToHead(int dt) {
if (head == null) {
head = new Node(dt);
}
else {
head.prev = new Node(dt);
head.prev.next = head;
head = head.prev;
}
}
public static void main(String args[]) {
DLL dll = new DLL();
dll.insertToHead(1);
dll.insertToHead(2);
dll.insertToHead(3);
}
}
Please, somebody, tell me what to change in the beginning of the class.
are we gone use extends or implements Comparable<E> or what!
and what changes should i do the method insertToHead(Comparable)
what changes should i do to the main.
You would probably like to look into how generics work as well. The basic idea is that you would like to set up your class so that it will not know exactly the specific type of object but can be given some hint at the types of things it can expect of a declared generic type.
In your case, you would like to set up your list so that you can create linked lists of anything that can be compared. Java has a class for that which you have mention called Comparable<E> this tells Java that it will be able to call such methods as compareTo on the provided object.
More specifically to your closing questions:
Use the following style of class declaration MyClass<MyGenericType extends Comparable<MyGenericType>>. In your case DLL<E extends Comparable<E>>.
Switch the method arguments to accept E our declared generic type.
You should use the class Integer instead of the primitive type int, and change the creation of your list to DLL<Integer> dll = new DLL<Integer>().
Fully updated version of provided code:
public class DLL<E extends Comparable<E>> {
class Node {
Node next;
Node prev;
E data;
Node() {
next = null;
prev = null;
data = null;
}
Node(E dt) {
next = null;
prev = null;
data = dt;
}
}
Node head;
void insertToHead(E dt) {
if (head == null) {
head = new Node(dt);
}
else {
head.prev = new Node(dt);
head.prev.next = head;
head = head.prev;
}
}
public static void main(String args[]) {
DLL<Integer> dll = new DLL<Integer>();
dll.insertToHead(1);
dll.insertToHead(2);
dll.insertToHead(3);
}
}
This new implementation should provide a hint for how to proceed with some of the other homework tasks. For instance you can now compare objects just by their compareTo method which might useful for sorting hint hint.
That doc page gives a very good explanation for how to use this method. You should note that in their docs, they use a generic type called T instead of E, it really doesnt make a difference you can call it whatever you want provided it is unique to your program.
Edit:
An each hint in the sorting direction:
Ojbects which extend the Comparable class have a method which is called compareTo this method is set up so you can call:
object1.compareTo(object2);
this method returns an int which will be:
> 0 when object1 is greater than object2
= 0 when object1 is equal to object2
< 0 when object1 is less than object2
I don't want to give away too much as this is a homework assignment but here is my hint:
The way the above code sets up your classes, you would be able to tell the relationship between NodeA and NodeB by calling:
NodeA.data.compareTo(NodeB.data)
this will return an integer which gives your information according to the list above.
The <=,>=,== operators are likely found in the Integer class's compareTo method.
Something like:
public int compareTo(Object o) {
int otherNumber = ((Integer) o).intValue();
int thisNumber = this.intValue();
if (otherNumber > thisNumber) {
return 1;
} else if (otherNumber < thisNumber) {
return -1;
} else {
return 0;
}
}
but more likely they just do something like:
public int compareTo(Object o) {
return this.intValue() - o.intValue(); // possibly normalized to 1, -1, 0
}
See the Docs on Integer for more info on this.

Anyone know why this method for linked list keeps on going forever?

I have this linked list method that is used to insert before, so it takes a node and puts it before the beforeNode. Currently it does that, but then it goes on forever and makes the linked list infinitely big when it should only be four long. Does anyone see why it keeps on going?
private void insertBefore(Node aNode, Node beforeNode)
{
if(this.getPrevious(beforeNode) != null) {
this.getPrevious(beforeNode).setNext(aNode);
// aNode.setPrevious(beforeNode);
//this.getPrevious(this.getPrevious(beforeNode)).setNext(aNode);
} else {
head = aNode;
}
aNode.setNext(beforeNode);
// beforeNode.setPrevious(aNode);
}
Here is the print list method that could have something to do with it, but I dont think so
public void printList()
{
Node currentNode;
currentNode = this.getHead();
System.out.print("head ->");
while(currentNode!=null)
{
System.out.print(currentNode.getData().toString()+ " -> ");
currentNode = currentNode.getNext();
}
System.out.println("|||");
}
I think some how you are passing the same node for both aNode and beforeNode. In java, every object is a reference. Did you by any chance try to create aNode a copy of beforeNode ? It might have made both the same and causing the linked list to have a self loop. use a copy constructor or things like clone to get a duplicate node.

Recursive Tree Traversal Method With Return Type Array

Is there a way to recursively traverse a tree and return an array that is scoped to that recursive method?
So I recently answered someone else's question on this topic. That question can be found here: SO Question. My solution uses an array outside of the scope of the recursion, and therefore the method cannot (or at least probably should not) return the array. However, is there a way to write a recursive method for traversing trees such that it returns an array? Even writing an initial method that calls the recursive one would be fine, but I can't think of a good way to do this.
Here's the code that I suggested before:
private List nodeValues = new ArrayList();
public void traversePreRecursive(BinarySearchTreeNode node)
{
if (node != null)
{
nodeValues.add(node.getValue());
traversePreRecursive(node.getLeft());
traversePreRecursive(node.getRight());
}
}
As you can see the ArrayList is outside of the scope of the recursion - And therefore returning it doesn't make a lot of sense. Is there a better way to do this?
public static List traversePreRecursive(Node node) {
if (node == null) return new ArrayList();
List nodeValues = new ArrayList();
nodeValues.add(node.getValue());
nodeValues.addAll(traversePreRecursive(node.getLeft()));
nodeValues.addAll(traversePreRecursive(node.getRight()));
return nodeValues;
}
There is an alternative, but it involves two passes over the tree. You would only employ this alternative if the array operations in my first answer were giving you grief. This approach starts by providing an index for each of the nodes (the index() method) -- basically working out which element of the array a node should occupy before we actually create the array. This also gives me a count of nodes (size). I then allocate an array (list) big enough to hold all the nodes and pass it into a method (addToList) that copies the node-references into the previously identified element in the array.
public static List<Node> getNodes(Node a) {
int size = index(a, 0);
List<Node> list = new ArrayList<Node>(size);
addToList(a, list);
return list;
}
private static int index(Node node, int index) {
if (node == null) return index;
node.setIndex(index);
int iLeft = index(node.getLeft(), index++);
int iRight = index(node.getRight(), iLeft++);
return iRight + 1;
}
private static void addToList(Node node, List<Node> list) {
if(node == null) return;
list.add(node.getIndex(), node);
addToList(node.getLeft(), list);
addToList(node.getRight(), list);
}
In c you can have static function variables,(Ie, adding a value to a list in one iteration of a function means that that value will be in the list in the next iteration--if the list is static) but using them isn't the best (most optimal) solution for the problem you are suggesting. So, I think you are searching for static variables, but this isn't an appropriate case to use them.

Categories

Resources