Linked List adding elements at certain points - java

I'm trying to implement a LinkedList, the problem I'm having is adding elements to this list, I've already added elements in the main class and want to know how to add elements at the beginning of the list and at the end of the list. The current is able to print, but when i add new elements they cant be seen. I also want to know about getting the size of the linked list.
class Node {
int data;
Node next;
Node(int data){
this.data = data;
}
}
public class LinkedList {
Node head;
int size;
public void AddBeginning(int data) {
Node newNode = new Node(data);
newNode.next = head;
this.size++;
head = newNode;
}
public void addAtEnd(int data) {
Node current = head;
while(current.next != null) {
current = current.next;
}
current.next = new Node(data);
}
public void getSize() {
System.out.println(size);
}
public void printList(Node head) {
Node current = head;
while (current !=null) {
System.out.print(current.data + "-->");
current = current.next;
}
System.out.print(current);
}
}
public class Tester {
public static void main(String[] args) {
LinkedList ll = new LinkedList();
Node head = new Node(25);
Node second = new Node(22);
Node third = new Node(7);
head.next = second;
second.next = third;
ll.AddBeginning(20);
ll.printList(head);
}
}
I would like to add 20 at the beginning and another integer at the end.

You are adding to Node 20 ll.AddBeginning(20); to LinkedList.head And Trying to print the list using Tester.head (declared in main method)
Solution:
Step 1 : Initialize LinkedList.head either
- Using constructor or
LinkedList ll = new LinkedList(head);
public LinkedList(Node head) {
this.head = head;
}
- Assign head to LinkedList object i.e., ll
ll.head = head; // Need to initialize Linked List with Head
Step 2 : No need to pass head variable to printList() function. It prints the LinkedList.head elements
ll.printList(); //Here you passing Tester.head not required
Code :
Tester main method
ll.head = head; // Need to initialize Linked List with Head
ll.AddBeginning(20); //Here actually adding node to linkedList head
ll.printList(); //Here you passing Tester.head not required
LinkedList.PrintList method
public void printList() {
Node current = this.head;//changed to linkedlist.head
while (current != null) {
System.out.print(current.data + "-->");
current = current.next;
}
System.out.print(current);
}

Related

I need to replace the array with the user input, but move the previous array to the right

public class LinkedList {
public Node head, tail;
//constructor method to create a list of object with head,
tail,
and size.
public LinkedList() {
head = null;
tail = null;
}
//method add node to end of list
public void addLastNode(int data) {
if (tail == null)
head = tail = new Node(data); //empty list
else {
tail.next = new Node(data); //link new node as last node
tail = tail.next; //make tail pointer points to last node
}
}
//method #1: add first node
public void addFirstNode(int data) {
Node temp = new Node(data);
if (tail==null)
tail = temp;
temp.next = head;
head = temp;
}
//method #2: add node at index
public void addAtIndex(int index, int data) {
if(index<countNodes()) {
if(index==0) {
Node temp = head;
head = new Node(data);
head.next = temp.next;
return;
}
//method #3: remove first node
public void removeFirstNode() {
Node a = head;
Node b = head.next - 1;
}
I have this code, and this only replaces the array for example..
[a.b,....d] the user enters replace a with d then the output should be like [d,a,b,.s.d] but my output just replaces it..
how do i change that
for method 3

Not printing elements when value of n is equal to size of linked list

I am doing the program for removing nth element from end of the linked list. But problem is that when my size of lined list is equal to n then it is not returning head.next. Where I am doing wrong?
class Main{
static class Node {
int data;
Node next;
Node(int data){
this.data = data;
this.next = null;
}
}
Node head = null;
public void addFirst(int data) {
Node newnode = new Node(data);
if(head ==null){
head = newnode;
return;
}
newnode.next = head;
head = newnode;
}
//print list
public void PrintLL() {
Node n = head;
if(n.next==null){
System.out.println("NULL");
return;
}
while(n!=null){
System.out.print(n.data+ " --> ");
n= n.next;
}
}
//Find nth node from last
public Node RemoveNthNode(Node head,int nth){
if(head.next==null){
return null;
}
int size=0;
Node curNode=head;
while(curNode!=null){
curNode = curNode.next;
size++;
}
if(nth==size){
return head.next;
}
Node prevnode = head;
int i=1;
while(i<size-nth){
prevnode=prevnode.next;
i++;
}
prevnode.next = prevnode.next.next;
return head;
}
public static void main(String[] args) {
Main ll = new Main();
ll.addFirst(90);
ll.addFirst(40);
ll.addFirst(45);
System.out.println("\n");
ll.RemoveNthNode(ll.head, 3);
ll.PrintLL();
}
}
I tried the code that I have posted but it is not printing when n equal size of LL.
The reason is that although your function RemoveNthNode returns the head after the removal, the caller (in main) ignores the returned value, so that it never sees a change to head. The confusion may also be caused by the parameter that has the name head, which shadows the head property of the class instance.
As it is not intuitive that the caller needs to provide head as argument, while you would expect that the method would know what the head of the list is, I suggest to make it a void method which doesn't take the head argument.
You should also take care of the case where head is null.
Your PrintLL has a problem too: it doesn't print the node when the list has just one node.
Corrected code:
public void PrintLL() {
Node n = head;
while(n!=null){
System.out.print(n.data+ " --> ");
n= n.next;
}
System.out.println("NULL");
}
public void RemoveNthNode(int nth){
if(head == null || head.next==null){
head = null;
return;
}
int size=0;
Node curNode=head;
while(curNode!=null) {
curNode = curNode.next;
size++;
}
if(nth==size){
head = head.next;
return;
}
Node prevnode = head;
int i=1;
while(i<size-nth){
prevnode=prevnode.next;
i++;
}
prevnode.next = prevnode.next.next;
}
public static void main(String[] args) {
Main ll = new Main();
ll.addFirst(90);
ll.addFirst(40);
ll.addFirst(45);
ll.PrintLL();
ll.RemoveNthNode(3);
ll.PrintLL();
}

Create a loop in a Java LinkedListArray and make the method detectLoop return true

Am having a lot of trouble creating node to complete a loop in this SinglyLinkedList after i checked whether it contains a loop with this method here detectLoop, The first call of this method returns an expected false because i created a SinglyLinkedList without a loop...So after printing out that boolean value, i tried to create a Node to loop the List but its still returning false, and then it says non-static member Node cannot be referenced from a static reference
class SinglyLinkedList {
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
//Represent the head and tail of the singly linked list
public Node head = null;
public Node tail = null;
//addNode() will add a new node to the list
public void addNode(int data) {
//Create a new node
Node newNode = new Node(data);
//Checks if the list is empty
if (head == null) {
//If list is empty, both head and tail will point to new node
head = newNode;
tail = newNode;
} else {
//newNode will be added after tail such that tail's next will point to newNode
tail.next = newNode;
//newNode will become new tail of the list
tail = newNode;
}
}
//display() will display all the nodes present in the list
public void display() {
//Node current will point to head
Node current = head;
if (head == null) {
System.out.println("List is empty");
return;
}
System.out.println("Nodes of singly linked list: ");
while (current != null) {
//Prints each node by incrementing pointer
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
//detectLoop method to check if the loop contains a loop and return boolean
public boolean detectLoop() {
Node fastPtr = head;
Node slowPtr = head;
while (fastPtr != null && fastPtr.next != null) {
fastPtr = fastPtr.next.next;
slowPtr = slowPtr.next;
if (slowPtr == fastPtr) {
return true;
}
}
return false;
}
public static void main(String[] args) {
SinglyLinkedList u = new SinglyLinkedList();
u.addNode(7);
u.addNode(6);
u.addNode(4);
u.display();
//First Check return false as expected
System.out.println("Does a loop exist in this linked list?" + " " + u.detectLoop());
//Link a last noe to first node so that a loop is formed and check with method
//This instantiation returns an error, please help
Node loopNode = new Node(7);
//The line above throws a non-static to static reference error so i cant create a loop
u.display();
System.out.println("Does it now contain a loop?" + u.detectLoop());
}
}

Java Simple Class to Return a Reversed Singly Linked List

I am trying to write a simple class that reverse a singly linked list and return a constructed linked list. The code below is working if i make everything public which I dont want to. Anybody interested to address my question? (should I use doubly linked list? or it is possible with single link list?)
What I want is a function reverseList receives a ListNode Object return a ListNode Object (in reverse order). Like this:
originalNumber=OriginalNumber.reverseList();
//// my code
public class ReverseLinkList {
public static ListNode originalNumber=new ListNode();
public static ListNode reversedNumber=new ListNode();
public static void main(String[] args) {
//create 1->2->3->null
originalNumber.add(1);originalNumber.add(2);originalNumber.add(3);
System.out.print(num1.toString()+"\n");
//create 3->2->1->null
reversedNumber=originalNumber.reverseList;
}
}
class ListNode{
private class Node{
Object data;
Node next;
Node(int v){
data=v;
next=null;
}
public Object getData(){
return data;
}
public void setData(int v){
data=v;
}
public Node getNext(){
return next;
}
public void setNext(Node nextValue){
next=nextValue;
}
}
private Node head;
public void add(int data){
if(head==null){
head=new Node(data);
}
Node temp=new Node(data);
Node current=head;
if(current !=null){
while(current.getNext()!=null){
current=current.getNext();
}
current.setNext(temp);
}
}
public String toString(){
String output="";
if(head!=null){
Node current=head.getNext();
while(current!=null){
//System.out.println(output);
output+=current.getData().toString();
current=current.getNext();
}
}
return output;
}
public Node getHead(){
return head;
}
public static 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;
}
}
The original and working code which I do not want
public class ReversedLinkedList {
static Node head;
static class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
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;
}
void printList(Node node) {
while (node != null) {
System.out.print(node.data + "");
node = node.next;
}
}
public static void main(String[] args) {
ReversedLinkedList list = new ReversedLinkedList();
list.head = new Node(1);
list.head.next = new Node(2);
list.head.next.next = new Node(3);
list.printList(head);
head = list.reverse(head);
System.out.println("");
list.printList(head);
}
}
You're on the right track. You can make the member variables private & use the appropriate getters & setters:
public ListNode reverseList() {
Node prev = null;
Node current = this.getHead();
Node next = null;
while (current != null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
head = prev;
return this;
}
This allows you print a reversed list:
System.out.println(originalNumber.reverseList());
Note that the originalNumber is itself manipulated. So, subsequent prints (System.out.println(originalNumber);) would still print the reversed list.
If you don't want the original to be modified, then there really isn't any other way apart from collecting all the data & then looping through in the reverse order & adding them into a new list:
public ListNode reverseList() {
int size = 0;
// Calculate size
Node current = this.getHead();
while (current != null) {
size++;
current = current.getNext();
}
int[] data = new int[size];
// Collect all data
current = this.getHead();
int index = 0;
while (current != null) {
data[index++] = current.getData();
current = current.getNext();
}
// Add to a new list in reverse order
ListNode reversed = new ListNode();
for (index = size - 1; index >= 0; index--)
reversed.add(data[index]);
return reversed;
}
That first scan to get the size can be skipped if size is tracked while adding elements to the list or by simply switching to an ArrayList instead of an array for data.
Finally there's the elegant recursive approach which also keeps the original ListNode intact:
public ListNode reverseRecursive() {
return recursive(this.getHead());
}
private ListNode recursive(Node node) {
if (node == null)
return new ListNode();
else {
ListNode listNode = this.recursive(node.next);
listNode.add(node.data);
return listNode;
}
}
To print:
System.out.println(originalNumber.reverseRecursive());
Here we needn't keep track of size & you make use of the call stack to naturally keep track & pop out the nodes in reverse.

How do I print out the data in my LinkedList

I have successflully created a LinkedList from scratch. So far it can only add data. No deletion or anything fancy like that.
I can add strings, integers etc but I have a problem with printing the data I have added. How do I do that? I guess I'll have to loop through it first, but how?'
Here is my Node class:
public class Node {
T data;
Node<T> nextNode;
public Node(T data) {
this.data = data;
}
public String toString () {
return data +"";
}
}
Here is the LinkedList class:
public class LinkedList <T> {
Node<T> head;
Node<T> tail;
public void add (T data) {
// where to add statements. if its empty or not
Node<T> node = new Node<T> (data);
if (tail == null) { // empty list
// nothng in the node = tail = node;
head = node;
tail = node;
}
else { // non empty list, add the new boogie train to the tail
tail.nextNode = node; // new node pointing to tail
tail = node; // update
}
}
And here is the main. Where I create an object out of Linkedlist and use the generic add method to add my data. But how do i print it out on the screen? Thanks in advance.
public static void main(String[] args) {
LinkedList<Object> list = new LinkedList<Object> ();
list.add(15); // boogie1 = head
list.add(16);
list.add(10); // boogie end = tail
Add a method toString to your LinkedList class
public String toString() {
Node<T> curr = head;
StringBuilder sb = new StringBuilder();
sb.append("LinkedList [");
while (curr != null) {
sb.append(curr.data);
if (curr.nextNode != null) {
sb.append(", ");
}
curr = curr.nextNode;
}
sb.append("]");
return sb.toString();
}
Then call it in your main method :
System.out.println(list.toString());
You have to override the toString() method in your LinkedList<T> class
Well, you can either implement the Iterator pattern: http://sourcemaking.com/design_patterns/iterator/java/1
Or you just implement a method that can either print the node element, or execute something on each of them, somewhat like this:
public class LinkedList <T> {
Node<T> head;
Node<T> tail;
public void add (T data) {
...
}
public void forEach(java.util.function.Consumer<T> consumer)
{
for(Node<T> currentNode = head; currentNode != null; currentNode = currentNode.nextNode)
//I am assuming the last node points to null in nextNode
// and that head is initialized to null if the list is empty
{
consumer.accept(currentNode);
}
}
}
Then just do
linkedList.forEach(x -> System.out.println(x.toString());
If everything is right, this should work in Java 8.
create a getter method in your LinkedList class.
public Node getHead() {
return head;
}
in your main()
public static void main(String[] args) {
LinkedList<Object> list = new LinkedList<>();
list.add(15); // boogie1 = head
list.add(16);
list.add(10); // boogie end = tail
Node node = list.getHead();
// Break the loop after the variable reaches null, i.e. end of list.
// The un initialised instance non-primitive variable is always null by default.
while(node != null) {
System.out.println(node); // Calls the toString() from class Node.
node = node.nextNode; // Move to next node.
}
}
Hope this works for you.

Categories

Resources