I am trying to write a simple linked list class that uses generic data type. I am new to Java so I can't figure out how to debug the error message in the main method that arises when I try to insert data into an instance of my class. The class code and the main method are as follows:
import java.io.*;
// Java program to implement
// a Singly Linked List
public class MyLinkedList<T> {
Node head; // head of the list
class Node<T> {
T data;
Node next;
// Constructor
Node(T d)
{
data = d;
next = null;
}
}
// Method to insert a new node
MyLinkedList insert(MyLinkedList list, T data)
{
// Create a new node with given data
Node new_node = new Node(data);
new_node.next = null;
// If the Linked List is empty,
// then make the new node as head
if (list.head == null) {
list.head = new_node;
}
else {
// Else traverse till the last node
// and insert the new_node there
Node last = list.head;
while (last.next != null) {
last = last.next;
}
// Insert the new_node at last node
last.next = new_node;
}
// Return the list by head
return list;
}
// Driver code
public static void main(String[] args)
{
/* Start with the empty list. */
MyLinkedList list = new MyLinkedList();
// Insert the values
list = insert(list, 1);
}
}
You need to change int to T in class declaration and method signature.
class MyLinkedList<T> {
MyLinkedList() {
head=null;
}
Node head; // head of list
class Node<T> {
T data;
Node next;
// Constructor
Node(T d) {
data = d;
next = null;
}
}
// Method to insert a new node
public void insert(T data) {
// Create a new node with given data
Node new_node = new Node(data);
new_node.next = null;
// If the Linked List is empty,
// then make the new node as head
if (this.head == null) {
this.head = new_node;
} else {
Node last = this.head;
while (last.next != null) {
last = last.next;
}
// Insert the new_node at last node
last.next = new_node;
}
}
protected void display() {
Node myNode=head;
System.out.println();
while (myNode != null) {
System.out.println(myNode.data);
myNode=myNode.next;
}
}
Change the insert method signature to the below:
public static void main(String[] args) {
/* Start with the empty list. */
MyLinkedList<Integer> list = new MyLinkedList<Integer>();
// Insert the values
list.insert(1);
list.insert(3);
list.insert(12);
list.insert(11);
list.insert(21);
list.insert(22);
list.insert(45);
list.display();
}
For clear coding and understanding I have changed class name as MyLinkedList
Related
This is the code I was given for the Singly Linked List, however I am struggling on completing the Reverse function. This was the code and my attempt at the reverse function. I keep getting 2 errors that say "Undeclared variable: node" and "imcompatible types: Node cannot be converted to Linkedlist".
class LinkedList
{
Node head;
Node current;
Node previous;
public Object Get()
{
return current != null ? current.GetData() : null;
}
public void Next()
{
if (current != null)
{
previous = current;
current = current.next;
}
}
public void Head()
{
previous = null;
current = head;
}
public void Insert(Object data)
{
Node node = new Node(data);
node.next = current;
if (current == head)
head = node;
else
previous.next = node;
current = node;
}
public void Remove()
{
if (current == null)
throw new RuntimeException("Invalid position to remove");
if (current == head)
head = current.next;
else
previous.next = current.next;
current = current.next;
}
public void Print()
{
for (Head(); Get() != null; Next())
System.out.println(Get());
}
public LinkedList Reverse()
{
Node previous = null;
Node current = node;
Node forward;
while (current != null)
{
forward = current.next;
current.next = previous;
previous = current;
current = forward;
}
return previous;
}
}
There is also class Node:
class Node
{
// Public reference to next node
public Node next;
// Private data field
Object data;
Node(Object data)
{
this.data = data;
}
public Object GetData()
{
return data;
}
}
And this is the main function:
class Test
{
public static void main(String args[])
{
// creating a singly linked list
LinkedList linked_list = new LinkedList();
// adding node into singly linked list
linked_list.Insert(Integer.valueOf(10));
linked_list.Next();
linked_list.Insert(Integer.valueOf(11));
linked_list.Next();
linked_list.Insert(Integer.valueOf(12));
// printing a singly linked
linked_list.Print();
// reversing the singly linked list
linked_list.Reverse();
// printing the singly linked list again
linked_list.Print();
}
}
Here is a simple solution:
public class ListReverser {
public static Node<Integer> reverse(Node head) {
Node current = head;
while(current.getNext() != null) {
Node next = current.getNext();
current.setNext(next.getNext());
next.setNext(head);
head = next;
}
return head;
}
}
When I try to implement a method to remove duplicates, it returns the linked list with the duplicates still in. I'm not sure if it is a problem of variable assignment or potentially the show() method that I have created.
https://www.dropbox.com/s/2cjj4nb4v8i5fg9/RemoveDuplicates.zip?dl=0
public class LinkedList {
LinkedListNode head;
//generating add method to
public void add(int data) {
LinkedListNode newNode = new LinkedListNode();
newNode.data = data;
newNode.next = null;
if (head == null) {
head = newNode;
}
else {
LinkedListNode current = head;
while(current.next != null) {
current = current.next;
}
current.next = newNode;
}
}
public void show() {
LinkedListNode newNode = head;
while(newNode.next != null) {
System.out.println(newNode.data);
newNode = newNode.next;
}
System.out.println(newNode.data);
}
}
public class Test {
public static void main(String[] args) {
LinkedListNode head = new LinkedListNode();
//12 and 5 are duplicates
LinkedList list = new LinkedList();
list.add(5);
list.add(45);
list.add(12);
list.add(12);
list.add(5);
list.add(33);
list.add(12);
list.add(45);
list.show();
removeDuplicates(head);
list.show();
}
public static void removeDuplicates(LinkedListNode head) {
LinkedListNode current = head;
LinkedListNode runner = null;
while (current != null) {
runner = current;
while (runner.next != null) {
if (runner.next.data == current.data) {
runner.next = runner.next.next;
}
else {
runner = runner.next;
}
}
current = current.next;
}
}
}
The head in your main method is not the same one as the head inside your linked list.
The head in your main method is always empty and you are not modifying list at all.
I need to write JUnits in order to test the reverse method of a singly linked list. This is the code I have for the link list
class ReversedLinkedList {
static Node head;
static class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
/* Function to reverse the linked list */
Node reverse(Node node) {
Node prev = null;
Node current = node;
Node next = null;
while (current != null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
node = prev;
return node;
}
// prints content of double linked list
void printList(Node node) {
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
}
public static void run(ReverseLinkedList list, Node head) {
head = list.reverse(head);
list.printList(head);
}
public static void main(String[] args) {
ReverseLinkedList list = new ReverseLinkedList();
list.head = new Node(85);
list.head.next = new Node(15);
list.head.next.next = new Node(4);
list.head.next.next.next = new Node(20);
run(list, head);
}
}
Now I want to make JUnits in order to test the reverse method, but I I am not sure how I should do it. Should I refactor the code somehow to achieve this? So far, this is what is in my test class:
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import ReverseLinkedList.Node;
class ReverseLinkedListTest {
#BeforeEach
void setUp() throws Exception {
}
#Test
void testReversion() {
ReverseLinkedList list = new ReverseLinkedList();
list.head = new Node(85);
list.head.next = new Node(15);
list.head.next.next = new Node(4);
list.head.next.next.next = new Node(20);
} }
But my test class does not even compile, I get the following error:
Multiple markers at this line
- Node cannot be resolved to a type
- The static field ReverseLinkedList.head should be accessed in a
static way
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
}
Trying to implement single-linked-list in below program, i am really not able to undertsand how to add a node in an Linked list (for start, m trying it on empty linked list).
To put it plain simple,i tried to setData and setNext but getSizeofList() return 0 everytime....its really looking like a rocket science to me now!!
Question : Can some-one tell me how to implement it....or rather, add a node to existing linked list....
What i have tried so far and why they dint worked out: i referenced multiple programs but they were too complex for me to understand(rocket science), so wrote below program from what i understood from algorithms....but even in algo's, they just show methods on how to implement and this is where i failed, as, i dont understand,what data-type and value is to be passed for adding a node...
please not that m not a java guy, so please go easy, this question comes in as an attempt to learn
package Data_S;
public class Linked_List {
private int data;
private Linked_List next_ptr;
private Linked_List headNode = null;
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Linked_List ll = new Linked_List();
//ll.setnext(25);
ll.insert_node(24);
ll.traverse();
ll.getSizeofList();
}
//size of list
public void getSizeofList()
{
int l = 0;
Linked_List curr = headNode;
while(curr != null)
{
l++;
curr = curr.getnext();
}
System.out.print("Size of list is = "+l);
}
//insert node
public void insert_node(/*Linked_List node, */int data)
{
if(headNode == null)
{
System.out.println("in insert"); // checking
this.setnext(headNode);
this.setData(data);
System.out.print("value = "+this.getData());
}
}
//set data for this node
public void setData(int data)
{
this.data = data;
}
//return the data
public int getData()
{
return this.data;
}
//set next pointer
public void setnext(Linked_List next_ptr)
{
this.next_ptr = next_ptr;
}
//get next pointer
public Linked_List getnext()
{
return this.next_ptr;
}
}
You have to make a distinction between the single chains (Node) of a linked list, and the entire container (LinkedList).
public class LinkedList {
Node head;
int size; // Maybe
public void insertAtEnd(int data) {
Node previous = null;
for (Node current = head; current != null; current = current.next) {
previous = current;
}
Node baby = new Node(data);
if (previous == null) {
head = baby;
} else {
previous.next = baby;
}
++size;
}
public void insertInSortedList(int data) {
Node previous = null;
Node current = null;
for (current = head; current != null && data < current.data;
current = current.next) {
previous = current;
}
Node baby = new Node(data);
baby.next = current;
if (previous == null) {
head = baby;
} else {
previous.next = baby;
}
++size;
}
}
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
}
}
One may sometimes see encapsulation as:
public class LinkedList {
private static class Node {
}
...
}
You never set headnode. In insertnode you just use setnext which does not set headnode. You are mixing the top class and the node implementation together.
Here is an example of how to implement a linked list in java for further reference:
How do I create a Linked List Data Structure in Java?