I have created a Doubly Linked List, and I am trying to call the getData method from the Linked List. However it is not working. I am trying to get this from the node. Here is the code from the Node.
private class Node<AnyType>
{
AnyType data;
Node<AnyType> next;
Node<AnyType> previous;
//Creates the Node with the parameters of data next and previous
public Node(AnyType data,Node<AnyType> next, Node<AnyType> previous )
{
this.data = data;
this.next = next;
this.previous = previous;
}
//Getters and setters for data next and previous
public AnyType getData() {
return data;
}
public Node<AnyType> getNext() {
return next;
}
public Node<AnyType> getPrevious() {
return previous;
}
public void setData(AnyType data) {
this.data = data;
}
public void setNext(Node<AnyType> next) {
this.next = next;
}
public void setPrevious(Node<AnyType> previous) {
this.previous = previous;
}
}
It may be a problem that it says that setData(AnyType data), is never used locally, however im not sure on that.
Now to where im trying to use the getData method. This is in an animate method,
if (USE_LINKED_LIST)
{
for (int i = 0; i < this.linked_list.size(); i++)
{
Movable current = this.linked_list.getData();
current.move(frame_rate_duration);
if(current.dead())
{
this.linked_list.remove(current);
i--;
}
}
}
The this.linked_list.getData() is giving me the error saying I must create method getData() in DoublyLinkedList. Im sure this is just a simple error but anything helps! thanks!
Here is the entire LinkedList class
package Our_Fireworks;
/**
*
* #author Ben Hammond
*
* #param <AnyType>
*/
public class DoublyLinkedList <AnyType>
{
private Node<AnyType> header;
private Node<AnyType> footer;
public DoublyLinkedList()
{
//Creates the header Node with data set to null, next set to footer, previous set to null
header = new Node<AnyType>(null, footer, null);
footer = new Node<AnyType>(null, null, header);
}
// Creates the insert method used to insert a Node into the linked list
public void insert(AnyType data)
{
//Creates a new node to insert before the footer
Node<AnyType> newNode = new Node<AnyType>(data, footer, footer.previous);
//Sets the node previous to footer, to link to the new Node
footer.previous.setNext(newNode);
//Sets the footer node to be linked to the new Node
footer.setPrevious(newNode);
}
//Remove method to remove a Node from the linked list
public void remove (AnyType data)
{
//Starts the iteratorLooper from the first Node in the list
Iterator<AnyType> iteratorLooper = first();
//Runs the while loop as long as valid = true
while(iteratorLooper.valid())
{
//Once you receive the correct data, the loop will stop
if(iteratorLooper.getData().equals(data))
{
break;
}
//Goes to the next data member
iteratorLooper.next();
}
//Once the while loop breaks, it will delete that data member
iteratorLooper.remove();
}
//Creates the size method
public int size()
{
//Creates an int variable
int count = 0;
//Starts the iteratorLooper at the first Node
Iterator<AnyType> iteratorLooper = first();
//As long as valid returns true the while loop will run
while(iteratorLooper.valid())
{
//Will add to the count variable
count++;
//Goes to the next Node
iteratorLooper.next();
}
//Returns the count once the while loop is complete
return count;
}
//Creates the first method
public Iterator<AnyType> first()
{
//Creates a new Iterator, at header.next
Iterator<AnyType> newIterator = new Iterator<AnyType>(header.next);
//Returns the Iterator
return newIterator;
}
//Creates the last method
public Iterator<AnyType> last()
{
//Creates a new Iterator at footer.previous
Iterator<AnyType> newIterator = new Iterator<AnyType>(footer.previous);
//Returns the Iterator
return newIterator;
}
//Iterator find method
public Iterator<AnyType> find(AnyType data)
{
Iterator<AnyType> iteratorLooper = first();
//As long as valid returns true the while loop runs
while(iteratorLooper.valid())
{
//runs the loop until data is equal to "getData"
if(iteratorLooper.getData().equals(data))
{
break;
}
iteratorLooper.next();
}
//Returns iteratorLooper
return iteratorLooper;
}
//Creates the Node class
private class Node<AnyType>
{
AnyType data;
Node<AnyType> next;
Node<AnyType> previous;
//Creates the Node with the parameters of data next and previous
public Node(AnyType data,Node<AnyType> next, Node<AnyType> previous )
{
this.data = data;
this.next = next;
this.previous = previous;
}
//Getters and setters for data next and previous
public AnyType getData() {
return data;
}
public Node<AnyType> getNext() {
return next;
}
public Node<AnyType> getPrevious() {
return previous;
}
public void setData(AnyType data) {
this.data = data;
}
public void setNext(Node<AnyType> next) {
this.next = next;
}
public void setPrevious(Node<AnyType> previous) {
this.previous = previous;
}
}
//Creates the Iterator class
public class Iterator<AnyType>
{
//Creates a new node of currentNode
private Node<AnyType> currentNode;
public Iterator(Node<AnyType> currentNode)
{
this.currentNode = currentNode;
}
//Creates the valid method
public boolean valid()
{
//Checks to see if current node is not equal to the header footer, or null
if (currentNode != header && currentNode != footer && currentNode != null)
{
//If the statement is true it returns true
return true;
}
else
{
//If it is not true... it simply returns false
return false;
}
}
//Creates the next method
public void next()
{
//Checks if the next Node is not equal to null
if(currentNode.getNext() != null)
{
//Gets the next node, of what ever the current node is
currentNode = currentNode.getNext();
}
}
//Creates the previous method
public void previous()
{
//Checks if the previous Node is not equal to null
if(currentNode.getPrevious() != null)
{
//Gets the previous node of currentNode
currentNode = currentNode.getPrevious();
}
}
public AnyType getData()
{
//Gets the data inside the currentNode
return currentNode.getData();
}
//Creates the remove method
public void remove()
{
//As long as valid returns true than the if statement will run
if(valid())
{
currentNode.getPrevious().setNext(currentNode.getNext());
currentNode.getNext().setPrevious(currentNode.getPrevious());
currentNode = currentNode.getPrevious();
}
}
//Creates the insert method with the parameters of AnyType and data
public void insert(AnyType data)
{
//Creates a newNode to be inserted after currentNode
Node<AnyType> newNode = new Node<AnyType>(data, currentNode.next, currentNode );
currentNode.getNext().setPrevious(newNode);
currentNode.setNext(newNode);
}
}
}
You have getData() method for Node, not for your linked list class. I think you meant something like
Movable current = this.linked_list.get(i).getData();
(Provided your linked list class has a getter for index)
Usually linked lists don't have random access getters, so most likely the whole code should be written differently:
for (Node<Movable> node = linked_list.getHead(); node != null; node = node.getNext()) {
Movable current = node.getData();
...
}
EDIT: So you have getData() in your Iterator:
for (Iterator<Movable> iter = linked_list.first(); iter.valid(); iter.next()) {
Movable current = iter.getData();
...
}
Related
I need to implement a Node class, where the basic methods are: getItem(), getNext(), setItem() and setNext(). I want the nodes to be able to store at least the default integer range in Java as the “item”; the “next” should be a reference or pointer to the next Node in a linked list, or the special Node NIL if this is the last node in the list.I also want to implement a two-argument constructor which initializes instances with the given item (first argument) and next node (second argument) , I've kind of hit a brick wall and need some guidance about implementing this , any ideas ?
I have this so far:
class Node {
public Node(Object o, Node n) {
}
public static final Node NIL = new Node(Node.NIL, Node.NIL);
public Object getItem() {
return null;
}
public Node getNext() {
return null;
}
public void setItem(Object o) {
}
public void setNext(Node n) {
}
}
While implementing the custom LinkedList/Tree, we need Node. Here is demo of creating Node and LinkedList. I have not put in all the logic. Just basic skeleton is here and you can then add more on yourself.
I can give you a quick hint on how to do that:
Class Node{
//these are private class attributes, you need getter and setter to alter them.
private int item;
private Node nextNode;
//this is a constructor with a parameter
public Node(int item)
{
this.item = item;
this.nextNode = null;
}
// a setter for your item
public void setItem(int newItem)
{
this.item = newItem;
}
// this is a getter for your item
public int getItem()
{
return this.item;
}
}
You can create a Node object by calling:
Node newNode = Node(2);
This is not a complete solution for your problem, the two parameter constructor and the last node link are missing, but this should lead you in the correct direction.
Below is a simple example of the Node implementation, (i renamed Item to Value for readability purpose). It has to be implemented somehow like this, because methods signatures seems to be imposed to you. But keep in mind that this is definely not the best way to implement a LinkedList.
public class Node {
public static final Node NIL = null;
private Integer value;
private Integer next;
public Node(Integer value, Node next) {
this.value = value;
this.next = next;
}
public Integer getValue() {
return this.value;
}
public Node getNext() {
return this.next;
}
public void setValue(Integer value) {
this.value = value;
}
public void setNext(Node next) {
this.next = next;
}
public boolean isLastNode() {
return this.next == Node.NIL || Node;
}
}
public class App {
public static void main(String[] args) {
Node lastNode = new Node(92, Node.NIL);
Node secondNode = new Node(64, lastNode);
Node firstNode = new Node(42, secondNode);
Node iterator = firstNode;
do () {
System.out.println("node value : " + iterator.getValue());
iterator = iterator.getNext();
} while (iterator == null || !iterator.isLastNode());
}
}
The node class that will be implemented changes according to the linked list you want to implement. If the linked list you are going to implement is circular, then you could just do the following:
public class Node {
int data;
Node next = null;
public Node(int data){
this.data = data;
}
}
Then how are you going to implement the next node?
You are going to do it in the add method of the circularLinkedList class. You can do it as follows:
import java.util.*;
public class CircularLinkedList {
public CircularLinkedList() {}
public Node head = null;
public Node tail = null;
public void add(int data) {
Node newNode = new Node(data);
if(head == null) {
head = newNode;
}
else {
tail.next = newNode;
}
tail = newNode;
tail.next = head;
}
public void displayList() {
System.out.println("Nodes of the circular linked list: ");
Node current = head;
if(head == null) {
System.out.println("Empty list...");
}
else {
do {
System.out.print(" " + current.data);
current = current.next;
}while(current != head);
System.out.println();
}
}
}
I'm trying to add several information into one Node in a singly linked list... How do I do that?
After asking the user for several vehicle information: plateNo(String), vehicleType(String), serviceType(String) I will have to store this information for each vehicle. I have to use a singly linked list to store all the vehicle entering and leaving the wash.
Then, my program should display all the vehicles entering and leaving the vehicle wash with their service order.
How do I do this?
This is my singly LinkedList:
public class LinkedList<T>
{
private Node<T> head; // first node in the linked list
private int count;
public int getCount() {
return count;
}
public Node getHead() {
return head;
}
public LinkedList() {
head = null; // creates an empty linked list
count = 0;
}
public void displayList(){
Node<T> current = head; // start at beginning
while(current != null) // until end of list,
{
System.out.print(current.getData() + " ");
current = current.getNext();
//move to next link
}
System.out.println("");
}
public Node deleteFront()
{
Node<T> temp = head;
if(head.getNext() == null) // if only one item
return null; // return null
head = head.getNext(); // first --> old next
count--;
return temp;
}
public void removeValue(T value)
{
Node<T> current = head, prev = null;
while (current != null)
{ //if current node contains value
if (value == current.getData())
{
//handle front removal (case 1)
if( prev == null)
head = current.getNext();
else //handle mid removal (case 2)
prev.setNext(current.getNext());
// prev node now points to maxNode's (a.k.a current) successor, removing max node.
break; // remove first occurence only
}
// update prev to next position (curr)
prev = current;
// move curr to the next node
current = current.getNext();
}
}
public void addFront(T n)
{
Node<T> newNode = new Node<T>(n);
newNode.setNext(head);
head = newNode;
count++;
}
}
My Node
public class Node<T> {
private T data;
private Node next;
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public Node(T data) {
this.data = data;
this.next = null;
}
}
I'm trying to add several information into one Node in a singly linked list... How do I do that?
... by thinking object-oriented! Create a class that models a vehicle:
class Vehicle {
String plateNo;
String vehicleType;
String serviceType;
// constructors, getters, setters, other methods ...
}
You have already a generic Node<T>, so use it:
Vehicle vehicle = callAwesomeMethodThatCreatesVehicleInstance();
Node<Vehicle> node = new Node(vehicle);
Now you can use such a node in your linked list.
Your code seems fine. You just need to define a new class that contains all the information that you want to store. As you have already made the Node class for a generic data type T, you can then insert the new class that you will make here.
class Details{
String plateNo;
String vehicleType;
String serviceType;
public Details(){
this.plateNo = "";
this.vehicleType = "";
this.serviceType = "";
}
}
Then in your code for the linked list:
public class LinkedList<T>
{
private Node<Details> head = new Details();
//rest of the class
}
I think I set up my class correct to be generic but when i try to call methods i cant seem to set up my other methods correct. Im I supposed to cast my variables to be generic? or do I cast my methods to variables?
public class LinkedList<E>
{
// reference to the head node.
private E head;
private int listCount;
public boolean delete(E string)
// post: removes the element at the specified position in this list.
{
Node current = head.getNext();
while(true){
if(current == null){
return false;
}else if(current.getNext().getData().equals(string)){
if(current.getNext() == null){
current.setNext(null);
}else{
current.setNext(current.getNext().getNext());
}
listCount--; // decrement the number of elements variable
return true;
}else{
current = current.getNext();
}
}
}
private class Node<E extends Comparable<E>>
{
// reference to the next node in the chain,
E next;
// data carried by this node.
// could be of any type you need.
E data;
// Node constructor
public Node(E _data)
{
next = null;
data = _data;
}
// another Node constructor if we want to
// specify the node to point to.
public Node(E _data, E _next)
{
next = _next;
data = _data;
}
// these methods should be self-explanatory
public E getData()
{
return data;
}
public void setData(E _data)
{
data = _data;
}
public E getNext()
{
return next;
}
public void setNext(E _next)
{
next = _next;
}
}
}
The types of your variables were a bit messed up.
Node.next needs to be a Node
LinkedList.head needs to be Node
Node does not need to be generic. (The E type parameter is in scope for the inner class.)
Here's a version that compiles:
class LinkedList<E> {
// reference to the head node.
private Node head;
private int listCount;
public boolean delete(E string)
// post: removes the element at the specified position in this list.
{
Node current = head;
while (true) {
if (current == null) {
return false;
} else if (current.getData().equals(string)) {
if (current.getNext() == null) {
current.setNext(null);
} else {
current.setNext(current.getNext().getNext());
}
listCount--; // decrement the number of elements variable
return true;
} else {
current = current.getNext();
}
}
}
private class Node {
// reference to the next node in the chain,
Node next;
// data carried by this node.
// could be of any type you need.
E data;
// Node constructor
public Node(E _data) {
next = null;
data = _data;
}
// another Node constructor if we want to
// specify the node to point to.
public Node(E _data, Node _next) {
next = _next;
data = _data;
}
// these methods should be self-explanatory
public E getData() {
return data;
}
public void setData(E _data) {
data = _data;
}
public Node getNext() {
return next;
}
public void setNext(Node _next) {
next = _next;
}
}
}
Looking at your delete method, I think it's a bit buggy though. When you arrive at a node where the data equals string, you change the next-pointer of that node while you should be changing the next-pointer of the previous node.
I would try something like this:
Node current = head, prev = null;
while (current != null) {
if (current.getData().equals(string)) {
// Remove current from list
if (current == head) {
head = current.getNext();
} else {
prev.setNext(current.getNext());
}
listCount--; // decrement the number of elements variable
return true;
}
prev = current;
current = current.getNext();
}
My first assignment in my programming class is about writing code for a Doubly Linked List, which includes writing an add, remove, size, iterator first, iterator last, and iterator find functions. I have spent 3 hours and gotten no where in understanding this. I understand what happens if I can see it in a picture. But my problem is translating it to code. This is what I have so far:
public class DoublyLinkedList< G > {
public class node {
G data;
node next;
node prev;
public node(G data, node next, node prev) {
this.data = data;
this.next = next;
this.prev = prev;
}
}
node header;
node footer;
public DoublyLinkedList() {
header = new node(null, null, null);
footer = new node(null, header, null);
header.next = footer;
}
public void add(G data) {
header.next = new node(data, footer.prev, footer);
}
public int size() {
node current = header.next;
int quanity = 0;
if (current == null) {
return 0;
}
while (current != null) {
current = current.next;
quanity++;
}
return quanity;
}
public static void main(String args[]) {
DoublyLinkedList<Integer> test = new DoublyLinkedList<Integer>();
//test.add(new Integer(2));
//test.add(new Integer(22));
//test.add(new Integer(222));
System.out.println(test.size());
}
}
As you can see, I've been using the main() to test everything. From what I've been told by my teacher, my constructor and node class look fine. However I know either my add and size are not right because when I test this, when there is no nodes in the list, it displays nothing, but it should display 0 right? I mean, assuming my size code is right, which I'm not sure of.
And whenever I add a node, no matter how many I add, it always displays 1. So either both add and size are broken, or both are. I have not written the other functions as it makes no sense until I figure these ones out. Please someone help me understand this! Thank you.
Declare a size field in DoublyLinkedList to store the current size of the list. When add succeed, make size++. When remove succeed, make size--. And size() method just simply return the value of size.
The sample code is here:
private int size = 0;
public void add(G data) {
header.next = new node(data, footer.prev, footer);
size++;
}
public int size() {
return size;
}
Noticed couple of things:
First, footer is not constructed correctly. It should be:
public DoublyLinkedList() {
..
footer = new node(null, null, header);
// your code is incorrectly creating a circular list
..
}
Secondly add() method doesn't look correct. It should be something like :
public void add(G data) {
Node newNode = new Node(data, header, null);
header.prev = newNode
header = newNode;
}
// for adding at the front (LIFO)
OR
public void add(G data) {
Node newNode = new Node(data, null, footer);
footer.next = newNode
footer = newNode;
}
//for adding at the tail (FIFO)
Check out the wikipedia entry for doubly linked lists. It has some good pseudo code.
Using your own code I'm going to make a few suggestions
public class DoublyLinkedList< G > {
public class node {
G data;
node next;
node prev;
public node(G data) {
this.data = data;
this.next = null;
this.prev = null;
}
}
node header;
node footer;
public DoublyLinkedList() {
header = new node(null);
footer = new node(null);
header.next = footer;//link the header to the footer
footer.prev = header;//link the footer to the header
}
public void add(G data) { //assuming you are adding the node to the head of the list
node newNode = new node(data); //creating new node to add with the data
newNode.next = header.next; // setting new node to head of the list or the footer
newNode.prev = header; //setting the new node's previous node to the header
header.next = newNode; //setting the newNode as the next node.
}
public int size() {
node current = header.next;
int quantity = 0;
if (current.data == null/*Empty list*/) { //you needed to specify what you were trying to test
return 0;
}
while (current.data != null/*traversing the list*/) {
current = current.next;
quantity++;
}
return quantity;
}
public static void main(String args[]) {
DoublyLinkedList<Integer> test = new DoublyLinkedList<Integer>();
//test.add(new Integer(2));
//test.add(new Integer(22));
//test.add(new Integer(222));
System.out.println(test.size());
}
}
Here you go:
public class DoublyLinkedList {
private class Node {
String value;
Node next,prev;
public Node(String val, Node n, Node p) {
value = val;
next = n;
prev=p;
}
Node(String val) {
this(val, null, null);
}
}
private Node first;
private Node last;
public DoublyLinkedList() {
first = null;
last = null;
}
public boolean isEmpty(){
return first==null;
}
public int size(){
int count=0;
Node p=first;
while(p!=null){
count++;
p=p.next;
}
return count;
}
public void add(String e) {
if(isEmpty()){
last=new Node(e);
first=last;
}
else{
last.next=new Node(e, null, last);
last=last.next;
}
}
public void add(int index, String e){
if(index<0||index>size()){
String message=String.valueOf(index);
throw new IndexOutOfBoundsException(message);
}
if(index==0){
Node p=first;
first=new Node(e,p,null);
if(p!=null)
p.prev=first;
if(last==null)
last=first;
return;
}
Node pred=first;
for(int k=1; k<=index-1;k++){
pred=pred.next;
}
Node succ=pred.next;
Node middle=new Node(e,succ,pred);
pred.next=middle;
if(succ==null)
last=middle;
else
succ.prev=middle;
}
public String toString(){
StringBuilder strBuilder=new StringBuilder();
Node p=first;
while(p!=null){
strBuilder.append(p.value+"\n");
p=p.next;
}
return strBuilder.toString();
}
public String remove(int index){
if(index<0||index>=size()){
String message=String.valueOf(index);
throw new IndexOutOfBoundsException(message);
}
Node target=first;
for(int k=1; k<=index;k++){
target=target.next;
}
String element=target.value;
Node pred=target.prev;
Node succ=target.next;
if(pred==null)
first=succ;
else
pred.next=succ;
if(succ==null)
last=pred;
else
succ.prev=pred;
return element;
}
public boolean remove(String element){
if(isEmpty())
return false;
Node target=first;
while(target!=null&&!element.equals(target.value))
target=target.next;
if(target==null)
return false;
Node pred=target.prev;
Node succ=target.next;
if(pred==null)
first=succ;
else
pred.next=succ;
if(succ==null)
last=pred;
else
succ.prev=pred;
return true;
}
public static void main(String[] args){
DoublyLinkedList list1=new DoublyLinkedList();
String[] array={"a","c","e","f"};
for(int i=0; i<array.length; i++){
list1.add(array[i]);
}
list1.add(1,"b");
list1.add(3,"d");
System.out.println(list1);
}
}
Ok guys I need to write a method; MyLinkedList getFirst(int n) – Returns a linked list of the first n elements. If the list is empty or n > size return null.
and I'm lost, I've done the mothods add, remove, add to middle, print a string of elements, and so on but this one has me stuck..
all I have so far is:
public MyLinkedList<E> getFirst(int n) {
if(n > size ) {
return null;
}
Node<E> current = head;
for (int i = 0; i == n; i++) {
current.next = new Node<E>(e);
}
}
I know this code is pretty wrong but its all I can think of been working on this assignment for a while and I'm just running out of steam I guess lol
Thanks for any and all help.
Create an empty list
Add the head to the list
Continuing adding the next node to the list until you have the first n nodes.
public MyLinkedList getFirstN(int n) {
MyLinkedList firstNList=new MyLinkedList();//create an empty list
if(n>size)
firstNList= null;
else {
Node tmp=head; //initialise tmp Node to the head(beginning) of list
for(int i=0;i<n;i++) {
firstNList.add(tmp);//add current node to the end of list
tmp=tmp.getNext();
}
}
return firstNList;
}
Implement the add(Node node) method to append a Node to the end of list.
You can use this as prototype and proceed with any operation
public class Node {
private int data;
private Node next;
public Node(int data) {
this.data = data;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public Node(int data, Node next) {
this.data = data;
this.next = next;
}
}
public class LinkedList {
private Node start;
public LinkedList() {
start = null;
}
public void insert(int x) {
if(start == null) {
start = new Node(x, start);
} else {
Node temp = start;
while(temp.getNext() != null) {
temp = temp.getNext();
}
Node newNode = new Node(x,null);
temp.setNext(newNode);
}
}
public void getFirst() {
if(start == null) {
System.out.println("\n List is empty !!");
}
else {
Node temp = start;
System.out.println("\n First Element is --->" + temp.getData());
}
}
}
public class MainClass {
public static void main(String[] args) {
LinkedList ll = new LinkedList();
System.out.println("\n--- Inserting 100 ---\n");
ll.insert(100);
ll.insert(101);
ll.insert(102);
ll.insert(103);
System.out.println("\n--- First Element ---\n");
ll.getFirst();
}
}