How compiler is knowing about head in linkedlist - java

How here head is automatically got the address of the node when we did not pointed we just created a node with name head
`we are directly using the head as if head is not equal to null do this but how head is getting any value in it thats my question.
public class Main {
public int size ;
Main(){
this.size=0;
}
Node head;
class Node{
String data;
Node next;
Node(String data){
this.data= data;
this.next=null;
size++;
}
}
// add in first
public void addFirst(String data){
Node Newnode = new Node(data);
if (head == null){
head = Newnode;
return;
}
Newnode.next=head;
head=Newnode;
}
}

Related

Reversing a singly linked list?

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;
}
}

Creating push() method for Stack class with Node class

I'm doing an assignment that I have to create my own Stack class using a Node class, I'm doing the push() method. Here is my code:
For class Node:
class Node{
//attributes
private String data;
private Node next;
//basic constructor
Node(){
}
Node(String data){
this.data = data;
this.next = null;
}
//accessors
public String getData(){
return this.data;
}
public Node getNext(){
return this.next;
}
//mutators
public void setData(String tmpData){
this.data = tmpData;
}
public void setNext(Node tmpNext){
this.next = tmpNext;
}
This is the method push I did so far:
class MyStack{
//attributes
private Node top;
//constructor
MyStack(){
this.top = null;
}
//method to push a node into the stack
public void push(Node node){
Node next = node.getNext();
next = this.top;
this.top = node;
}
public void print() {
// Check if it's empty
if (this.top == null) {
System.out.println("Stack is empty.");
} else {
Node tmp = this.top;
while(tmp != null) {
System.out.print(tmp.getData()+ " ");
tmp = tmp.next;
}
System.out.println();
}
}
}
The main class that I use for testing:
class Main{
public static void main(String[] args) {
MyStack stack = new MyStack();
stack.push(new Node("1"));
stack.push(new Node("2"));
stack.push(new Node("3"));
stack.print();
}
}
Can you guys have a look at my push method, because when I print, the only value I get is 3, I want the output to be 3 2 1. Thanks a lot
run this in the debugger, and you will see:
//method to push a node into the stack
public void push(Node node){
Node next = node.getNext(); //If node is a new node, next is going to be null
next = this.top; // here you are just setting the variable you declared about to this.top. This erases setting next to node.getNext()
this.top = node; // here you are setting this.top to node. You need to first set node.next = top
}
What you want is:
//method to push a node into the stack
public void push(Node node){
node.setNext(this.top);
this.top = node; // now node is the top, and node.next is the previous top
}
Make sure to set node.next first, or you won't be able to connect node to all the rest of the nodes in the stack

Doubly Linked List, Insert Before A Given Node in Java

The method not working:
public void insert_before_node(Node givenNode, int data) {
Node newNode = new Node(data);
newNode.prev = givenNode.prev;
givenNode.prev = newNode;
newNode.next = givenNode;
if(newNode.prev != null)
newNode.prev.next = newNode;
}
Another add method which is working:
public void insert_front(int data) {
Node newNode = new Node(data);
newNode.next = head;
newNode.prev = null;
if(head != null)
head.prev = newNode;
head = newNode;
}
A print method to debug:
public void print() {
Node n = head;
while(n != null){
System.out.println(n.data);
n = n.next;
}
}
DoublyLinkedList class:
public class DoublyLinkedList {
static class Node {
int data;
Node next;
Node prev;
Node(int data) {
this.data = data;
this.next = null;
this.prev = null;
}
}
Node head;
DoublyLinkedList() {
this.head = null;
}
public static void main(String[] args) {
DoublyLinkedList ll = new DoublyLinkedList();
ll.insert_front(0);
ll.insert_before_node(ll.head, 100);
ll.print();
}
}
LinkedList and Node implementations are very straightforward. Find here: https://www.geeksforgeeks.org/doubly-linked-list/
I first create a linkedlist, insert_front() a value to make the head not null, then use the method above to insert something else. Insertion to front, end, after a node are working, however, this insert_before_node() is not working. What I have inserted with this method is not appears on my print.
I draw on a paper too, still couldn't find the problem.
The geeksforgeeks link also has no java implementation for this method.
Your code is working, apart from the assignment of head in insert_front(Node,int) method, I think you forgot this. before that.
Plus, maybe you would need to
remove the head argument in insert_front method (it's the head of the dll, it has a class member for that),
remove the underscores (not Java good practice, Sonar would complain)
return the nodes you create so you can later reference them (and possibly create a fluent API)
A basic rework would look like this MVP:
import java.util.Objects;
public class DoubleLinkLists {
public static void main(String[] args) {
DoubleLinkedList dll = new DoubleLinkedList();
DoubleLinkedList.Node node5 = dll.insertInFront(5);
DoubleLinkedList.Node node4 = dll.insertInFront(4);
DoubleLinkedList.Node node2 = dll.insertInFront(2);
DoubleLinkedList.Node node1 = dll.insertInFront(1);
DoubleLinkedList.Node node3 = dll.insertBefore(node4, 3);
System.out.println(dll);
}
public static class DoubleLinkedList {
Node head;
#Override
public String toString() {
Node current = head;
StringBuilder sb = new StringBuilder();
while (current != null) {
sb.append(current.data)
.append(" ");
current = current.next;
}
return sb.toString();
}
public Node insertBefore(Node givenNode, int data) {
Node newNode = new Node(data);
newNode.prev = givenNode.prev;
givenNode.prev = newNode;
newNode.next = givenNode;
if (newNode.prev != null) {
newNode.prev.next = newNode;
}
return newNode;
}
public Node insertInFront(int data) {
Node newNode = new Node(data);
newNode.next = head;
newNode.prev = null;
if (head != null) {
head.prev = newNode;
}
head = newNode;
return newNode;
}
public static class Node {
int data;
Node prev;
Node next;
Node(int d) {
data = d;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Node node = (Node) o;
return data == node.data;
}
#Override
public int hashCode() {
return Objects.hash(data);
}
}
}
}
I edit the code for more readable.
public void insert_before_node(Node next, int data) {
Node newNode = new Node(data);
Node prev = next.prev;
//left to right
prev.next = newNode;
newNode.next = next;
//traverse right to left
next.prev = newNode;
newNode.prev = prev;
}
I assume the next and prev is also not null.
By the way, you should add more condition to detect null(next and prev) in insert_before_node.
Please update the result and hope it help.

Learning LinkedList and Nodes, but I keep getting a "cannot be resolved or is not in field" error on newNode in buildList method

I've been trying to figure this out for a few days, and everything I do is wrong.
I keep getting a "cannot be resolved or is not in field" error for the .next on newNode.next in buildList method.
I am also getting this same error for the .next and the .data on the current.next/ current.data in the printList method.
What I have is what is in the book, but it does not want to work in Eclipse.
Please help...
package linkedList;
import java.util.*;
import org.w3c.dom.Node;
public class ListOne {
//This part needs various options:
//Build list
//clear list
//check if the list is sorted
//insert at head
static Scanner input = new Scanner(System.in);
public static Node head;
public int linkedListCount = 0;
//public static LinkedList<Integer> intList = new LinkedList<Integer>();
private class MyNode{
private int data;
private Node next;
public MyNode(int data){
this.data = data;
this.next = null;
}
}
//BUILD LIST
public void buildList(int value){
Node newNode = (Node) new MyNode(value);
newNode.next = head;
head = newNode;
}
//Clear the list
public void clearList(){
head = null;
}
public void printList () {
if(head == null){
return;
}
Node current = head;
while (current != null) {
// visit
System.out.println(current.data);
current = current.next;
} // traversal
} // printList
public boolean isEmpty(){
return head == null;
}
}
Here is the errors I am receiving.
In method buildList, on newNode.next = "next cannot be resolved or is not a field." / In method printList, on current.data = "data cannot be resolved or is not a field." / In method printList, on current.next = "next cannot be resolved or is not a field."
I don't see any point in using the Node interface at all. Just use MyNode throughout:
package linkedList;
import java.util.*;
//import org.w3c.dom.Node; No need for this
public class ListOne {
// .....
public static MyNode head;
private class MyNode{
private int data;
private MyNode next;
public MyNode(int data){
this.data = data;
this.next = null;
}
}
//BUILD LIST
public void buildList(int value){
MyNode newNode = new MyNode(value);
newNode.next = head;
head = newNode;
}
// etc....
}

Implementing a Generic Double Linked Class with refer to current obeject

For an assignment we were asked to implement a fully generic DoubleLinkedList class, and there was a part where I was unsure of that I need help with. I tried to search online, but I was unable to find an answer.
For the addToEnd and addToFront methods, they each have the return type as BasicDoubleLinkedList and should return a "reference to the current object"
When I try to retun a node, it doesn't allow me to because its not a BasicDoubleLinkedList object. I need to use "this" however, I am unsure how to actually go about doing it.
Here is my code so far
*my inner class node
public class Node <T>
{
private T data;
private Node<T> next;
private Node<T> prev;
public Node()
{
}
}
public class BasicDoubleLinkedList<T> {
private Node<T> head; // points to the head node
private Node<T> tail; // points to the last node
int size;
public BasicDoubleLinkedList<T> addToFront(T data)
{
Node<T> newNode = new Node<T>();
newNode.data = data;
if(head == null)
{
head = newNode;
}
else{
head.prev = newNode;
newNode.next = head;
head = newNode;
}
return null; <------------ I am getting a bit confused somewhere, as I am not sure what to put for the return type that is BasicDoubleLinkedList<T>
}
}

Categories