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();
}
}
}
Related
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.
I am attempting to implement a linked list that uses a node class containing head, tail, and current nodes. Part of the linked list is an add method that should add a value to the end of the current node in the list just like an actual linked list would. My issue is that it only works for the first node and then just stops there. For example, in my main I tried testing the code by calling add(1); and add(2);. The console shows me 1 but that's all. I'm unsure if the error is in my add method, toString method, or node class.
I'll also add that I tested whether the correct values were being assigned to "current" in either case, and they were. This has led me to wonder if it's the toString that is the root of the issues, however no matter how much I try I can't change it to make any improvements.
I've hoping fresh eyes may be able to find any blaring issues that may exist.
Add method:
public void add(int val){
if(current != null){
Node nextNode = new Node(val, current);
current = nextNode;
tail = nextNode;
}
else{
head = tail = new Node(val, null);
current = head;
}
}
Node class:
public class Node{
public int data;
public Node next;
public Node(int d, Node next) {
this.data = d;
this.next = next;
}
}
toString:
public String toString(){
for(Node x = head; x != null; x = x.next){
System.out.println(x.data);
}
All:
public class IntLList extends IntList{
public IntLList(){
}
public class Node{
public int data;
public Node next;
public Node(int d, Node next) {
this.data = d;
this.next = next;
}
}
Node head = null;
Node tail = null;
Node current = null;
public void add(int val){
if(current != null){
Node nextNode = new Node(val, current);
current = nextNode;
tail = nextNode;
}
else{
head = tail = new Node(val, null);
current = head;
}
}
public int get(int index){
return 0;
}
public void set(int index, int val){
}
public void remove(int index) throws ArrayIndexOutOfBoundsException{
}
public int size(){
return 0;
}
public String toString(){
for(Node x = head; x != null; x = x.next){
System.out.println(x.data);
}
return "temp";
}
public void removeLast(){
}
public boolean isEmpty(){
boolean isEmpty = false;
if(head == null){
isEmpty = true;
}
return isEmpty;
}
public void clear(){
}
public static void main(String[] args) {
IntLList i = new IntLList();
i.add(1);
i.add(2);
i.toString();
}
}
Make the following changes:
public class Node{
public int data;
public Node next;
public Node(int d, Node next) {
this.data = d;
this.next = NULL; // this is to set the next node of current node to null
if(next!=NULL)
next.next=this; // this is to set the previous node to point to current node
}
}
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
}
My problem is in the add method. I think I know what I want it to do but I can't figure out what type of loop I should use to look through the list. As you can see I started to make a if else loop but I couldn't figure out what I should use as the counter. I'm pretty sure I have the right logic in dealing with the add but I feel like I'm not quite there yet. I was thinking of using compareTo in some fashion.
import java.util.*;
public class OrderedLinkedList<E extends Comparable<E>>
{
private Node topNode;
private class Node
{
private E data;
private Node nextNode;
public Node(E data)
{
this.data = data;
nextNode = null;
}
}
public OrderedLinkedList()
{
topNode = null;
}
public boolean empty()
{
if(topNode == null)
return true;
return false;
}
public String toString()
{
String myString = "";
Node nextNode = topNode;
while(nextNode != null)
{
myString = topNode + " -> " + nextNode;
nextNode = topNode.nextNode;
}
return myString;
}
public void add(E data)
{
Node myNode = new Node(data);
Node priorNode = topNode;
Node currentNode = topNode;
if(___)
{
priorNode = currentNode;
currentNode = currentNode.nextNode;
}
else
{
priorNode.nextNode = myNode;
myNode.nextNode = currentNode;
}
}
}
Since you don't typically know the length of a linked list until you've walked down it, the usual thing would be to use a while loop (as you've done in your toString() method)
Perhaps using a doubly linked list would be more beneficial. Consider the following alterations to your class:
import java.util.*;
public class OrderedLinkedList<E extends Comparable<E>>
{
private Node head;
private Node tail;
private class Node
{
private E data;
private Node nextNode;
private Node prevNode;
public Node(E data)
{
this.data = data;
nextNode = null;
prevNode = null;
}
public void setNext(Node node)
{
this.nextNode = node;
}
public Node getNext()
{
return this.nextNode;
}
public void setPrev(Node node)
{
this.prevNode = node;
}
public Node getPrev()
{
return this.prevNode;
}
public E getData()
{
return this.data;
}
public int compareTo(Node that) {
if(this.getData() < that.getData())
{
return -1;
}
else if(this.getData() == that.getData()
{
return 0;
}
else
{
return 1;
}
}
}
public OrderedLinkedList()
{
head = new Node(null);
tail = new Node(null);
head.setNext(tail);
tail.setPrev(head);
}
public boolean empty()
{
if(head.getNext() == tail)
{
return true;
}
return false;
}
public void add(E data) {
Node tmp = new Node(data);
if(this.empty()) {
this.addNodeAfterNode(tmp, head);
} else {
Node that = head.getNext();
// this while loop iterates over the list until finding the correct
// spot to add the new node. The correct spot is considered to be
// when tmp's data is >= that's data, or the next node after 'that'
// is tail. In which case the node is added to the end of the list
while((tmp.compareTo(that) == -1) && (that.getNext() != tail)) {
that = that.getNext();
}
this.addNodeAfterNode(tmp, that);
}
}
private void addNodeAfterNode(Node addNode, Node afterNode)
{
addNode.setNext(afterNode.getNext());
afterNode.getNext().setPrev(addNode);
afterNode.setNext(addNode);
addNode.setPrev(afterNode);
}
}
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();
}