why it doesn't print ? LinkedList - java

i have a problem that the method in LinkedList class don't print anything.. and i'm trying hard to know what's the problem i hope someone help
the main class
public static void main(String[] args) {
LLnode a = new LLnode(10);
LLnode b = new LLnode(20);
LLnode c = new LLnode(50);
LinkedList List1 = new LinkedList();
List1.printAllNodes();
}
}
LinkedList class
public class LinkedList {
private LLnode head;
public LLnode gethead() {
return this.head;
}
public void sethead(LLnode LLnode) {
this.head = LLnode;
}
// Constructor
public LinkedList() {
head = null;
}
// Example Method to check if list is empty
public boolean isEmpty() {
return head == null;
}
public void printAllNodes() {
LLnode helpPtr = head;
while (helpPtr != null) {
System.out.print(helpPtr.getdata() + " ");
helpPtr = helpPtr.getnext();
}
why it dosn't print i tried so hard

This is because you never add any nodes to your LinkedList.
Code could be as follows. Beware, nodes will be added at the beginning of list.
Main class:
public static void main(String[] args) {
LLnode a = new LLnode(10);
LLnode b = new LLnode(20);
LLnode c = new LLnode(50);
LinkedList List1 = new LinkedList();
List1.add(a).add(b).add(c);
List1.printAllNodes();
}
}
LinkedList class:
public class LinkedList {
private LLnode head;
public LLnode gethead() {
return this.head;
}
public void sethead(LLnode LLnode) {
this.head = LLnode;
}
// Constructor
public LinkedList() {
head = null;
}
// Example Method to check if list is empty
public boolean isEmpty() {
return head == null;
}
public LinkedList add(LLnode node){
LLnode oldHead = this.head();
this.head = node;
node.setNext(oldHead);
return this;
}
public void printAllNodes() {
LLnode helpPtr = head;
while (helpPtr != null) {
System.out.print(helpPtr.getdata() + " ");
helpPtr = helpPtr.getnext();
}
}

Related

Recursively reversing a linkedlist [duplicate]

This question already has answers here:
Reversing a linked list in Java, recursively
(33 answers)
Closed 6 years ago.
I'm trying to reverse a LinkedList using recursive calls, please let me know where I'm going wrong, I'm not able to catch reversed LL head.
LLNode is a linkedlist node and ReverseLLRecursively.reverse is the function I wrote for reversing.
Here is my code:
public class LLNode {
private int data;
private LLNode next;
public LLNode(int data, LLNode next) {
this.data = data;
this.next = next;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public LLNode getNext() {
return next;
}
public void setNext(LLNode next) {
this.next = next;
}
#Override
public String toString() {
return data + "->[" + (next!=null?next.data:"") + "]";
}
}
public class ReverseLLRecursively {
public static LLNode newHead = new LLNode(-1, null);
public static LLNode reverse(LLNode head, LLNode newHead) {
if(head==null || head.getNext()==null) {
newHead = head;
return head;
}
LLNode node = reverse(head.getNext(), newHead);
node.setNext(head);
head.setNext(null);
return node.getNext();
}
public static void main(String[] args) {
LLNode ll = new LLNode(1,new LLNode(2, new LLNode(3, new LLNode(3, new LLNode(2, new LLNode(3, null))))));
reverse(ll , newHead);
System.out.println(newHead);
}
}
You are overcomplicating your problem and work with a local variable which has the same name as a static member. This should be simpler:
public static LLNode reverse(LLNode previous) {
if(previous==null) {
return null;
}
LLNode toReturn = (previous->getNext() == null) ? previous : reverse(previous.getNext());
previous.getNext().setNext(previous);
return toReturn;
}
Note, that toReturn will be the new head.
Making the reverse a method of LLNode, makes stuff somewhat easier.
You want to return the last value (and only the last) in your linked list. If you have it, return, otherwise go deeper until you have it. After you have the end, store it, setNext as you don't need the value of next anymore, return the end.
public LLNode reverse(LLNode previous) {
if(getNext()==null) {
setNext(previous);
return this;
}
LLNode returnValue = getNext().reverse(this);
setNext(previous);
return returnValue;
}
public static void main(String[] args) {
LLNode ll = new LLNode(1,new LLNode(2, new LLNode(3, new LLNode(3, new LLNode(2, new LLNode(3, null))))));
ll = ll.reverse(null);
System.out.println(ll);
}
Otherwise the static variant if you need it for whatever reason.
public static LLNode reverse(LLNode current) {
if(current.getNext()==null) {
return current;
}
LLNode returnValue = reverse(current.getNext());
current.getNext().setNext(current);
current.setNext(null);
return returnValue;
}
public static void main(String[] args) {
LLNode ll = new LLNode(1,new LLNode(2, new LLNode(3, new LLNode(3, new LLNode(2, new LLNode(3, null))))));
ll = reverse(ll);
System.out.println(ll);
}

Merge two Queues in Java

I have been working on this code to properly merge and print these two queues, but to no avail. If someone could help point me in the right direction or let me know what I am doing wrong, it would be most appreciated.
Node Class
public class Node<E> {
private E element;
private Node next;
public Node(E element, Node<E> next) {
// Do something here
this.element = element;
this.next = next;
}
public E getElement() {
return element;
}
public void setNextNode(Node<E> next) {
// Do something here
this.next = next;
}
public Node<E> getNextNode() {
// Replace return null with something useful
return next;
}
}
LinkedList class
public class LinkedListQueue<E> implements Queue<E> {
private Node<E> head;
private Node<E> tail;
private int size;
public LinkedListQueue() {
}
public void enqueue(E element) {
Node newNode = new Node(element, null);
if (size == 0) {
head = newNode;
} else {
tail.setNextNode(newNode);
}
tail = newNode;
size++;
}
public E dequeue() {
if (head != null) {
E element = head.getElement();
head = head.getNextNode();
size--;
if (size == 0) {
tail = null;
}
return element;
}
return null;
}
public E first() {
if (head != null) {
return head.getElement();
}
return null;
}
public int getSize() {
return size;
}
public void printList() {
if (head != null) {
Node currentNode = head;
do {
System.out.println(currentNode.toString());
currentNode = currentNode.getNextNode();
} while (currentNode != null);
}
System.out.println();
}
}
Queue Class
public interface Queue<E> {
public void enqueue(E e);
public E dequeue();
public E first();
public int getSize();
public void printList();
}
Main Class
public static void main(String[] args) {
LinkedListQueue q1 = new LinkedListQueue();
q1.enqueue(1);
q1.enqueue(2);
q1.enqueue(3);
q1.enqueue(4);
q1.enqueue(5);
q1.printList();
LinkedListQueue q2 = new LinkedListQueue();
q2.enqueue(6);
q2.enqueue(7);
q2.enqueue(8);
q2.enqueue(9);
q2.printList();
}
public static LinkedListQueue merge(LinkedListQueue q1, LinkedListQueue q2){
LinkedListQueue q3 = new LinkedListQueue();
LinkedListQueue merged = LinkedListQueue.merge(q1,q2);
}
}
Here is what I have put in my LinkedList class
public static LinkedListQueue merge(LinkedListQueue q1, LinkedListQueue q2) {
if (q1 == null) {
return (q2);
} else if (q2 == null) {
return (q1);
}
LinkedListQueue merge = new LinkedListQueue();
merge.enqueue(q1);
merge.enqueue(q2);
return merge;
}
And here is what I have put in my Main. Which now prints the two queues but prints out the node location and not what prints out when I call the other queues.
LinkedListQueue q3 = new LinkedListQueue();
q3 = LinkedListQueue.merge(q1,q2);
q3.printList();
Your problem is in this snippet of code:
public static LinkedListQueue merge(LinkedListQueue q1, LinkedListQueue q2){
LinkedListQueue q3 = new LinkedListQueue();
LinkedListQueue merged = LinkedListQueue.merge(q1,q2); //problematic line
}
Specifically the part LinkedListQueue.merge(q1,q2);. This syntax is saying to call the static method merge defined in the class LinkedListQueue. However, looking in your code for LinkedListQueue, I don't see a static merge method defined.
The way your code is written, it is expecting something like:
public class LinkedListQueue<E> implements Queue<E>{
public static LinkedListQueue<E> merge(LinkedListQueue<E> q1, LinkedListQueue<E> q2){
//definition here
}
//more class code
}
See here for more about static methods.

How to create 2 different linked list and print the intersection of both the linked list

import java.util.*;
public class Intersection
{
private Node head;
private Node head1;
private Node head2;
private Node current1;
private Node current2;
private int l1;
private int l2;
public Intersection()
{
head= new Node(null);
head1= new Node(null);
head2= new Node(null);
Node current1= head1;
Node current2= head2;
l1=0;l2=0;
}
public static void main(String[] args)
{
Intersection obj= new Intersection();
LinkedList<Object> list1 = new LinkedList<Object>();
LinkedList<Object> list2 = new LinkedList<Object>();
list1.add(3);
list1.add(6);
list1.add(9);
list1.add(15);
list1.add(30);
list2.add(10);
list2.add(15);
list2.add(30);
Object ans= obj.method(obj.head1, obj.head2);
System.out.println(ans);
}
public Object method(Node current1, Node current2)
{
int diff;
if(current1== null || current2== null)
{
return null;
}
while(current1.getNext() != null)
{
l1++;
current1=current1.getNext();
}
while(current2.getNext() != null)
{
l2++;
current2=current2.getNext();
}
if(l1>l2)
{
diff=l1-l2;
int j=0;
while(j<diff)
{
current1=current1.getNext();
j++;
}
}
else
{
diff=l2-l1;
int j=0;
while(j<diff)
{
current2=current2.getNext();
j++;
}
}
while(current1!= null || current2!= null)
{
if(current1.getData()==current2.getData())
return current1.getData();
current1=current1.getNext();
current2=current2.getNext();
}
return null;
}
private class Node
{
Node next;
Object data;
public Node(Object _data)
{
next= null;
data= _data;
}
public Node(Node _next, Object _data)
{
next= _next;
data= _data;
}
public Object getData()
{
return data;
}
public void setData(Object _data)
{
data = _data;
}
public Node getNext()
{
return next;
}
public void setNext(Node _next)
{
next = _next;
}
}
}
Above is my code to find out the intersection of the linked list in which there is no error.
I am having problem in how to create 2 different linked lists and then print the intersection of the linked list.
Please give some suggestions.
This is how to create LinkedList, where Object is the Type you would hold in your list:
LinkedList<Object> list1 = new LinkedList<Object>();
to create second LinkedList:
LinkedList<Object> list2 = new LinkedList<Object>();
After that you have two lists: list1 and list2,is this what you need?
Intersection:
list1.retainAll(list2);
and list1 will have the intersection :)

add method not working for linked list in Java

I'm trying to create a method that will add a node to my linked list. The method takes a String. This is the method that I created:
public void add(String x)
{
Node newNode = new Node();
newNode.element = x;
newNode.nextNode = firstNode;
firstNode = newNode;
}
Unfortunately, this code isn't working. Is there a way I can alter it to make it work?
Here are all the information I was provided with:
Linked List Class with Node inner-class:
class LinkedList implements StringCollection
{
private static class Node
{
public String element;
public Node nextNode;
public Node (String element)
{
this.element = element;
this.nextNode = null;
}
}
private Node firstNode;
public NodeStringCollection ()
{
firstNode = null;
}
//add method goes here
public String toString ()
{
String s = "";
Node node = firstNode;
while (node != null)
{
s = s + node.element + " ";
node = node.nextNode;
}
return s;
}
}
Tested Linked Class:
Class Test
{
public static void main(String [] args)
{
StringCollection sc = new LinkedList ();
sc.add (new String ("A"));
sc.add (new String ("B"));
sc.add (new String ("C"));
sc.add (new String ("D"));
System.out.println (sc);
int countStrings = sc.size ();
System.out.println (countStrings);
}
}
The Output
D C B A
4
I fixed your code. What you did wrong is that the element that you added to the LinkedList replaced the old firstNode. So the last node that you add to your implementation would become the new first node. Therefore, your LinkedList printed D C B A which is the reverse of what it should be.
The code below stores the first node and the last node. When a new node is added, we let the last node point to the newly created node and then set the last node to the newly created node:
Code
public class LinkedList {
public static class Node {
public String element;
public Node nextNode;
public Node(String element) {
this.element = element;
this.nextNode = null;
}
}
private Node firstNode;
private Node lastNode;
public LinkedList() {
firstNode = null;
lastNode = null;
}
public void add(String x) {
Node newNode = new Node(x);
if (firstNode == null)
firstNode = newNode;
if (lastNode != null)
lastNode.nextNode = newNode;
lastNode = newNode;
}
public String toString() {
String s = "";
Node node = firstNode;
while (node != null) {
s = s + node.element + " ";
node = node.nextNode;
}
return s;
}
}
Example code
public static void main(String args[]) throws Exception {
LinkedList sc = new LinkedList();
sc.add(new String("A"));
sc.add(new String("B"));
sc.add(new String("C"));
sc.add(new String("D"));
System.out.println(sc);
}
Output
A B C D

Confused about choosing a loop to iterate a linked list

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

Categories