Java Link-list head cannot found - java

Try to create an empty link list. To creating the empty list I create a inner class Node and made it static such that main class can access it.
import java.util.LinkedList;
public class Addtwo {
static class Node {
int data;
Node next;
Node head;
Node(int d) {
data = d;
next = null;
// Constructor
}
public static void main (String args[])
{
/* Start with the empty list. */
LinkedList llist = new LinkedList();
llist.head = new Node(1);
Node second = new Node(2);
Node third = new Node(3);
llist.head.next = second;
second.next = third;
}
}
}
It cannot find the node head that I create within the inner class Node. How to solve this?
Error:
Error :(22, 22) java: cannot find symbol
symbol : variable head
location: variable llist of type java.util.LinkedList

First, if you want to use the JDK's LinkedList, you don't need to manage the nodes of the list, this work is already implemented. You only need to do this:
LinkedList<Integer> llist = new LinkedList<Integer>();
llist.add(1);
llist.add(2);
llist.add(3);
And there is more functionality here.
Second, if you want to implement your own linked list (I think this is what you want), you donĀ“t need to use the JDK's LinkedList, you can start with this basic code:
public class Addtwo {
static class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
public static void main(String args[]) {
/* Start with the empty list. */
Node head = new Node(1);
Node second = new Node(2);
Node third = new Node(3);
head.next = second;
second.next = third;
Node iterator = head;
while (iterator != null) {
System.out.println(iterator.data);
iterator = iterator.next;
}
}
}
}
PS: You don't need to store a head for each node. You probably need another class LinkedListManager to implement some methods and store the head and the tail of the list.

Related

How to print whole list after calling addfirst method?

How do i correct my addFirst method and also how can i make my removeFirst method work as it wont remove? How should i implement it?
public class LinkedList{
public static void main(String[] args) {
LinkedList l = new LinkedList();
l.addFirst("c");
//l.removeFirst("m");
l.addFirst("b");
System.out.println(l.first.data);
System.out.println(l.first.data);
}
public Node first;
static class Node {
String data;
Node next;
}
private void addFirst(String s){
Node newNode = new Node();
newNode.data=s;
newNode.next=first;
first= newNode;
}
private void removeFirst(String s){
//Node n1 = new Node();
first.next = null;
}
}
I want outcome to be :
b
c
but only b is printed.
You are printing the same value twice try this:
System.out.println(l.first.next.data);
In your linked list class, the first (or head) node will contain the next node so you'll have to call the first node and then call next nodes data.
Example:
LinkedList l = new LinkedList();
l.addFirst("c");
l.addFirst("b");
l.addFirst("z");
System.out.println(l.first.data);
System.out.println(l.first.next.data);
System.out.println(l.first.next.next.data);
Return linkedlist by each function except main.
After adding or removing node you have to return the linkedlist in main function then you can print whole linkedlist

Reverse LinkList whilst preserving original nodes

My teacher has assigned a program where I am to create a linked list of some random numbers. I am to create it from a list and then the second part of the assignment is to reverse it. The actual quote is
Write a Java method called reverseLinkedList() that will generate a
reversed linked-list from the linked-list that you create in problem
1. Your method should accept a linked-list as an input and return another linked list that has the node references in the reversed
order. Please do not print the original list in reverse. The idea is
to manipulate the node references so that the nodes are preserved in
same in order as they were originally created.
The code I have generated so far looks like
import java.util.*;
public class progassignment2
{
public static void main(String args[])
{
List<Integer> myList = new ArrayList<Integer>();
Random ran = new Random();
int ranNum;
for(int x = 0;x<5;x++)
{
ranNum = ran.nextInt(500);
myList.add(x,ranNum);
}
LinkedList<Integer> mylinklist = createLinkedList(myList);
System.out.println(mylinklist);
LinkedList<Integer> mylinklistrev = reverseLinkedList(mylinklist);
}
public static LinkedList createLinkedList(List<Integer> integerList)
{
LinkedList<Integer> linkedlist = new LinkedList<Integer>();
linkedlist.addAll(integerList);
return linkedlist;
}
public static LinkedList reverseLinkedList(LinkedList inputList)
{
for(int y = 0;y < inputList.size();y++)
{
inputList.addLast(inputList.pollFirst());
}
return inputList;
}
}
However I don't think I'm doing the assignment correctly, or that I understand what he is asking of me and unfortunately won't answer any questions and just cites "Read the assignment". Any help is greatly appreciated
What about:
public static LinkedList reverseLinkedList(List<Integer> inputList) {
LinkedList<Integer> reversedLinkedlist = new LinkedList<Integer>(inputList);
Collections.reverse(reversedLinkedlist);
return reversedLinkedlist;
}
Usually, exercises on linked lists do not make use of any built-in Java collection (like ArrayList, LinkedList, etc), but are instead meant to make you build your own collection type.
Your teacher probably wants you to build a very basic element, which would then become the building block of your own collection type: imagine an object where you can store a value and a reference to the following value in the list. In code:
class Node {
private int value;
private Node next;
public Node(int value){
this.value = value;
}
public int getValue(){
return value;
}
public Node getNext(){
return next;
}
public void setNext(Node next){
this.next = next;
}
}
Each element points to the next one, and the end of the list is marked by the last node's next element being null.
By using objects like this, you'll be able to define your own linked list, without using any pre-defined Collection offered by Java.
You've surely heard about the stack data structure: by reading all the elements in your linked list and putting them inside a stack, once the list will be over, you're going to fetch the elements inside the stack; creating a linked list in the order of the elements pulled from the stack will solve your problem of inverting the linked list.
The idea is to manipulate the node references so that the nodes are
preserved in same in order as they were originally created.
You should create your own LinkedList. You are not allowed to use common ways of reversing like using recursion, stack ,modifications or any collections interface methods.
here is the link includes LinkedList reversing ways and solution:
class LinkedList {
Node head; // head of list
/* Linked list Node */
class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
/* Function to print reverse of linked list */
void printReverse(Node head) {
if (head == null)
return;
// print list of head node
printReverse(head.next);
// After everything else is printed
System.out.print(head.data + " ");
}
/* Inserts a new Node at front of the list. */
public void push(int new_data) {
Node new_node = new Node(new_data);
new_node.next = head;
head = new_node;
}
public static void main(String args[]) {
LinkedList llist = new LinkedList();
llist.push(4);
llist.push(3);
llist.push(2);
llist.push(1);
llist.printReverse(llist.head);
}
}

Create new Node for Singly Linked List in Java

I am still learning Java, and currently working problems from Cracking the Coding Interview, and one of the problems on Chapter-2 (LinkedList) asks to remove duplicates from an unsorted linked List. I found a bunch of answers/solution on GitHub, but I would like to create my own Node, and write my own version.
What I have implemented so far is that I created Node class and write the function/method that can remove the duplicates from unsorted LinkedList, but when I try to test it, I tried to create the LinkedList in the main function, but I still have no idea how to figure it out. Can someone please help/guide me how to create a Singly LinkedList?
Basically, I create four nodes (fourth,third,second,head), and connect them all using the Node class.
Thanks in advance,
public class Node {
int data;
Node next;
public Node(int data, Node next){
this.data = data;
this.next = next;
}
public String toString(){
return data + "";
}
}
public class problem1 {
public void Remove_duplicates(Node head){
if(head == null){
return;
}
Node current = head;
while(current != null){
Node runner = current;
while(runner.next != null){
if(runner.next.data == current.data){
runner.next = runner.next.next;
}
else {
runner = runner.next;
}
}
current = current.next;
}
}
public static void main(String[] args) {
Node fourth = new Node(5,null);
Node third = new Node(3,fourth);
Node second = new Node(4,third);
Node head = new Node(3,second);
for(Node a: head){
// ERROR: saying can only iterate over an array (or) java.lang.Iterable
System.out.println(a.toString());
a = a.next;
}
}
}
Try another kind of loop e.g. while
Node head = new Node(3, second);
Node node = head;
while (node.next != null) {
System.out.println(node.toString());
node = node.next;
}
Like it explains it does not know how to iterate over your nodes.
Another approach for using the foreach would be to create an own class which implements the interface Iterable and does contain your LinkedList logic.
For the second approach I would suggest you to read the following: How can I implement the Iterable interface?

How can I add a node at the beginning of a doubly linked list in-between two dummy nodes?

I am trying to write a function addFirst() that takes an item and inserts it at the front of a doubly linked list. The doubly linked list has two dummy nodes, one on each end. The addFirst() method that I wrote so far only returns to two dummy nodes when I iterate through the list and print it. I cannot figure out what is wrong with my code.
public void addFirst(E item) {
if (item.equals(null)) { throw new NullPointerException(); }
Node node = new Node(item, null);
Node ptr = first;
ptr.next.prev = node;
node.prev = ptr;
node.next = ptr.next;
}
public static void main(String[] args) {
Deque<Integer> lst = new Deque<Integer>(); // empty list
lst.addFirst(1);
lst.addFirst(2);
lst.addFirst(3);
Iterator<Integer> it = lst.iterator(); // tests iterator method
while (it.hasNext()) {
Integer val = it.next();
System.out.println(val);
}
}
When I run main, all I get is:
null null
However, I expect:
null 3 2 1 null
Can anybody show me how I can fix my code so that I can add an item at the start of my doubly linked list in between the two dummy first and last nodes?
I found what I did wrong. I just needed to complete the chain by adding the line
ptr.next = node;
So my full code for this method looked like this:
public void addFirst(E item) {
if (item.equals(null)) { throw new NullPointerException(); }
Node node = new Node(item, null);
Node ptr = first;
ptr.next.prev = node;
node.prev = ptr;
node.next = ptr.next;
ptr.next = node;
}

Java LinkedList with generics

I have been trying to implement a singly linked list in java with generics and I tried to implement a method "headInsert()" to insert a new Node and make it the new head of the list.
I am trying to achieve this by creating a new Node and swapping it with the head.
However, I have an error while I am trying to parameterize the new Node.
Here is the code I have written and I would appreciate any sort of help I could get.
Thank you in advance.
package datastructures;
public class LinkedList<E> {
private Node head;
private Node tail;
private static class Node<E> {
E data;
Node next;
Node (E data) {
this.data = data;
}
}
//Insert at the beginning of a LinkedList
public void headInsert(Node n) {
if(head == null) {
head = n;
}
else {
Node temp = head;
Node n1 = new Node(n1.data); //error here
n1.next=head;
head=n1;
}
}
The error occurs because n1 was not created yet when you try to access n1.data, it should be:
Node n1 = new Node(n.data);
That said, you don't really need to create a new node to place in the head. You can implement headInsert() like this:
public void headInsert(Node n) {
n.next = this.head;
this.head = n;
}
Suppose you have an empty list (head is null) and you want to add node A, A.next will point to null, and head will point to A resulting in the list A->null
Now suppose you have a non-empty list, like A->B->C, and you want to insert node Z, Z.next will point to A, and head will point to Z so you will get Z->A->B->C.

Categories