LinkedList Deep copy java - java

I was trying to do the deep copy of my linked list known as DictionaryNode which I did but i was not able to display it's content in display method as it is always null. why DictinaryNode temp is always null ? and if i try to assign temp = head work but with temp = copy doesn't.
public class ListOfNodes {
public class DictionaryNode {
protected String word;
private int level;
private DictionaryNode next;
private int space = 0;
public void displayCopy() {
DictionaryNode temp = copy.next;
while( temp != null ) {
System.out.println(temp.word)
temp = temp.next;
}
}
public DictionaryNode( String word, int level ) {
this.word = word;
this.level = level;
next = null;
}
}
private DictionaryNode head = null;
public DictionaryNode copy = null;
//used to do deep copy
public void Clone() {
DictionaryNode temp = head.next;
while( temp != null ) {
copy = new DictionaryNode( temp.word , temp.level );
copy = copy.next;
temp = temp.next;
}
}
public void displayCopy() {
DictionaryNode temp = copy.next;
while( temp != null ) {
Sytem.out.println(temp.word)
temp = temp.next;
}
}

This program will demonstrate how to do a deep copy on a list. It's more generic than your specific example so hopefully it helps others too.
public class Java_Practice {
private static class LinkedListTest {
private String data;
private LinkedListTest next;
public LinkedListTest(String data) {
super();
this.data = data;
}
public String getData() {
return data;
}
public LinkedListTest getNext() {
return next;
}
public void setNext(LinkedListTest next) {
this.next = next;
}
#Override
public String toString() {
return "LinkedListTest [data=" + data + ", next=" + next + "]";
}
}
// Do a deep copy
private static LinkedListTest copyLlt(LinkedListTest original) {
LinkedListTest copy = new LinkedListTest(original.getData() + " copied");
LinkedListTest nextCopy = original.getNext();
LinkedListTest current = copy;
while (nextCopy != null) {
LinkedListTest newCopy = new LinkedListTest(nextCopy.getData() + " copied");
newCopy.setNext(nextCopy.getNext());
current.setNext(newCopy);
current = newCopy;
nextCopy = newCopy.getNext();
}
return copy;
}
public static void main(String[] args) {
LinkedListTest firstLlt = new LinkedListTest("First");
LinkedListTest secondLlt = new LinkedListTest("Second");
LinkedListTest thirdLlt = new LinkedListTest("Thrid");
firstLlt.setNext(secondLlt);
secondLlt.setNext(thirdLlt);
LinkedListTest copiedLlt = copyLlt(firstLlt);
// Data should say First, Second, Third
System.out.println("Original LinkedListTest: " + firstLlt.toString());
// Data should say First Copied, Second Copied, Third Copied
System.out.println("Copied LinkedListTest: " + copiedLlt.toString());
}
}

In your Clone method you never assign a next field for the copied content. You need to do this to have more than a single connected node in the copy. Furthermore you need to copy the head too. Moreover do must not overwrite copy with anything but the copy of the head:
copy = new DictionaryNode(null, head.level);
DictionaryNode temp = head.next;
DictionaryNode current = copy;
while( temp != null) {
DictionaryNode nn = new DictionaryNode( temp.word , temp.level);
current.next = nn;
current = nn;
temp = temp.next;
}

Related

(JAVA) How do I Remove the First Element in a Circular Doubly Linked List?

I've managed to make the doubly linked list into a circular one, I'm just having trouble making a method to remove the first element. I've tried looking at examples for single linked lists but I can't seem to modify it to fit my code. Any help would be greatly appreciated.
Linkedlist Class
package LinkedListS;
public class LinkedList {
private Node first;
private Node end;
LinkedList()
{
first = end = null;
}
public void addAtStart(int x){
Node temp = new Node(x);
if(first == null)
{
first = end = temp;
}
else
{
end.setNext(temp);
temp.setNext(first);
first = temp;
}
}
public void printFromStart()
{
Node temp = first;
do {
System.out.println(temp.getData());
temp = temp.getNext();
end.setNext(null);
} while (temp != null);
}
public void searchFromStart(int elementToBeSearched)
{
Node temp = first;
while(temp != null)
{
if (temp.getData() == elementToBeSearched)
{
System.out.println("Found " + elementToBeSearched);
return;
}
temp = temp.getNext();
}
System.out.println("Didn't find " + elementToBeSearched);
}
public void removeFirstElement(){
}
Driver Class:
enter code here
public class LinkedListMain {
public static void main(String[] args) {
LinkedList ll = new LinkedList();
System.out.println("Going to add elements At Start");
ll.addAtStart(5);
ll.addAtStart(7);
ll.addAtStart(9);
ll.addAtStart(10);
System.out.println("Print the doubly linked list elements");
ll.printFromStart();
System.out.println("Search the following elements");
ll.searchFromStart(7);
ll.searchFromStart(1289);
ll.removeFirstElement();
ll.printFromStart();
}
}
Node Class:
package LinkedListS;
public class Node {
private int data;
private Node next;
private Node prev;
// Constructor to intialize/fill data
public Node(int data)
{
this.data = data;
}
// set the address of next node
public void setNext(Node temp)
{
this.next = temp;
}
// get the address of next node
public Node getNext()
{
return this.next;
}
public Node getPrev()
{
return this.prev;
}
public void setPrev(Node temp)
{
this.prev = temp;
}
// to get data of current node
public int getData()
{
return this.data;
}
}
For the removeFirstElement method I've tried these solutions with no avail:
Attempt #1
Node temp = first;
temp = null;
Attempt #2
Node temp = first;
if(first != null){
if(temp.getNext() == first){
first = null;
}
} else {
first = end;
end = first.getNext();
}
Attempt #3
Node temp = first;
if (first == null) {
System.out.println("There is no first element to remove");
} else
temp = first;
System.out.println(temp);
Attempt #4
Node temp = first;
end = null;
if(first != null){
if(temp.getNext() == temp){
first = null;
}
} else {
end = first;
first = first.getNext();
}
After scanning a few other methods that is what I found that works:
public void removeFirstElement(){
if (first != null){
first = first.getNext();
} else {
System.out.println("There is nothing to be removed");
}
}

System printing to a certain index of a linkedList

I am working with java at the moment and I am trying to find out a way to stop printing to the console (for simplicity) after a certain index of a linkedList is reached. Any help explaining this would be much appreciated.
Below is my Node class used to create the list:
protected Integer data;
protected Node link;
public Node(Integer data, Node link) {
this.data = data;
this.link = link;
}
public Node addNodeAfter(Integer element) {
return link = new Node(element, link);
}
public String toString() {
String msg = "";
try {
if (link == null) {
msg = data + " null in tail";
} else {
msg = data + ", " + link.toString();
}
} catch (StackOverflowError e) {
// System.err.println("shit happened here");
}
return msg;
}
public Integer getData() {
return data;
}
public Node getLink() {
return link;
}
Create a method toString(int i) which takes as argument the number of elements which still have to be printed. If the argument is larger than zero and there is a valid link, then recursively call the toString(i - 1) method with i decreased by one:
Code:
public class Node {
public static void main(String[] args) {
Node linkedList = new Node(1, null);
Node node = linkedList;
for (int i = 2; i < 10; ++i)
node = node.addNodeAfter(i);
System.out.println(linkedList.toString(5));
}
public String toString(int i) {
if (i > 0) {
if (link == null)
return data.toString();
else
return data.toString() + " " + link.toString(i - 1);
} else
return "";
}
protected Integer data;
protected Node link;
public Node(Integer data, Node link) {
this.data = data;
this.link = link;
}
public Node addNodeAfter(Integer element) {
return link = new Node(element, link);
}
public Integer getData() {
return data;
}
public Node getLink() {
return link;
}
}
Output
1 2 3 4 5
You will need to extend the LinkedList class and override the toString() method, and then use your subclass.
Something like this:
public class MyLinkedList<E> extends LinkedList<E> {
#Override
public String toString() {
StringBuffer out = new StringBuffer("[");
for (int i=0; i < 3; i++) {
out.append(get(0).toString());
out.append(" ");
}
return out.toString();
}
}
And test it like this:
public class Main {
public static void main(String[] args) {
LinkedList<String> myList = new MyLinkedList<String>();
myList.add("one");
myList.add("two");
myList.add("three");
myList.add("four");
System.out.println(myList);
}
}

Priority Queue Generic

So I recently learnt about Generics and thought it would be cool to implement them in a Priority Queue. I am having a "Block" element which has a firstName and a data variable. The Node for the Priority Queue consists of Block, Next and Prev.
I am attaching the code below. I am almost exclusively getting "Should be parametrized" errors/warnings. And an error which says that my "Data" element cannot be resolved to a field, which probably means that I am unable to tell that I want Block as my "element E" in a Node. Any suggestions will be deeply appreciated
package QGen;
public class Block<E> implements Comparable<Block<E>> {
protected String firstName;
protected int data;
public Block(String firstName, int data) {
super();
this.firstName = firstName;
this.data = data;
}
#Override
public int compareTo(Block x) {
return (this.data - x.data);
}
}
package QGen;
public class PriorityQueue<E extends Comparable> {
protected Node<E> firstSentinel;
protected Node<E> lastSentinel;
protected class Node<E> {
protected Node<E> next;
protected Node<E> prev;
private E element;
public Node(E e, Node<E> previous, Node<E> nextt) {
element = e;
prev = previous;
next = nextt;
}
}
public PriorityQueue() {
firstSentinel = new Node<>(null, null, null);
lastSentinel = new Node<>(null, null, null);
firstSentinel.data = 11111;
lastSentinel.data = 0;
firstSentinel.prev = null;
firstSentinel.next = lastSentinel;
lastSentinel.prev = firstSentinel;
lastSentinel.next = null;
}
public void enQueue(E x) {
Node<E> newX = new Node<E>(x, null, null);
if (firstSentinel.next == lastSentinel)// list is empyty
{
firstSentinel.next = newX;
newX.prev = firstSentinel;
newX.next = lastSentinel;
lastSentinel.prev = newX;
} else {
Node<E> temp = newX;
Node<E> curr = firstSentinel.next;
while (curr != lastSentinel && temp.element.compareTo(curr) <= 0) {// <=comparison
// replaced
curr = curr.next;
}
Node<E> tempCurr = curr;
temp.next = tempCurr;
temp.prev = tempCurr.prev;
tempCurr.prev.next = temp;
tempCurr.prev = temp;
}
}
public E deQueue() {
if (firstSentinel.next == lastSentinel) {
return null;
} else {
Node<E> temp = new Node<E>(null, null, null);
temp = firstSentinel.next;
firstSentinel.next = temp.next;
temp.next.prev = firstSentinel;
return temp.element;
}
}
public void printt() {
Node<E> temp = new Node<E>(null, null, null);
temp = firstSentinel.next;
while (temp != lastSentinel) {
System.out
.println(temp.element.firstName + " " + temp.element.data);
temp = temp.next;
}
}
}
package QGen;
public class containsMain<E> {
public static void main(String[] args) {
PriorityQueue<Block> example = new PriorityQueue<Block>();
Block dequedObject = new Block<>(null, null);
Block<Block> incomingName = new Block<>("r", 1);
example.enQueue(incomingName);
dequedObject = (Block) example.deQueue();
}
}
I am aware that my PriorityQueue might not be the best of implementations and I will improve it. It is the Generics where I am unable to come up with a solution
Thanks
Without looking at the logic of your methods, I have several remarks regarding generics:
why is Block itself generic? It doesnt hold any generic field so remove it from Block!
new Node<>(null, null, null);
// this is a bad idea, change it to new Node<E>(null, null, null)
firstSentinel.data = 11111;
lastSentinel.data = 0;
//Those two cant work, because firstSentinel is referencing a Node<E> and not a Block! Delete those two rows, as they make no sense in your generic implementation of the Queue
Block<Block> incomingName = new Block<>("r", 1);
// This doesnt make sense, should be Block incomingName = new Block(...)

How to check if member exists

So i have implemented the insert method and it works just fine but my problem is how to check whether a member is already in the list or not,i want the program to check if the member is already in the list but the checker doesn't work. i want the program to put the member in team1 if the member is included in the list and Display "member does not exist" if the member is not on the list. I made a check method but it doesn't work. I am new in Programming and i really need help. Please enlighten me with your knowledge.
class Node
{
protected String info;
protected Node next;
public Node(String value)
{
info = value;
next = null;
}
}
class LinkedList
{
private Node head;
private int count;
public LinkedList()
{
head = null;
count = 0;
}
public void insert( String name)
{
Node a = new Node(name);
a.next = null;
count++;
if (head == null)
{
head = a;
return;
}
for(Node cur = head; cur != null; cur = cur.next)
{
if (cur.next == null)
{
cur.next = a;
return;
}
}
}
public void checker(String name)
{
for(Node cur = head; cur != null; cur = cur.next)
{
if(cur.info == name)
{
insertteam1(name);
System.out.print("OK");
}
else
{
System.out.print("member does not exist");
}
}
}
public void insertteam1(String name)
{
Node b = new Node(name);
b.next = null;
count++;
if (head == null)
{
head = b;
return;
}
for(Node cur = head; cur != null; cur = cur.next)
{
if (cur.next == null)
{
cur.next = b;
return;
}
}
}
In the code below,
if(cur.info == name){ // }
you are comparing the string info using == which is not the right way to compare strings in java.
Use
if(cur.info.equals(name)){ // }
or
use if(cur.info.equalsIgnoreCase(name)){ // } if you want to do case insensitive compare.

Inserting text file input into a linked list

Hey guys I am trying to read from a text file and store each name into a linked list node. When I read in the text file it reads the line, which is a name. I am trying to store each name into a linked list node. When I call the insertBack method and print it out, it shows that there is nothing in the nodes. Could anybody point me in the right direction, it would be much appreciated?
Here is the fileIn class:
import java.util.Scanner;
import java.io.*;
public class fileIn {
String fname;
public fileIn() {
getFileName();
readFileContents();
}
public void readFileContents()
{
boolean looping;
DataInputStream in;
String line;
int j, len;
char ch;
/* Read input from file and process. */
try {
in = new DataInputStream(new FileInputStream(fname));
LinkedList l = new LinkedList();
looping = true;
while(looping) {
/* Get a line of input from the file. */
if (null == (line = in.readLine())) {
looping = false;
/* Close and free up system resource. */
in.close();
}
else {
System.out.println("line = "+line);
j = 0;
len = line.length();
for(j=0;j<len;j++){
System.out.println("line["+j+"] = "+line.charAt(j));
}
}
l.insertBack(line);
} /* End while. */
} /* End try. */
catch(IOException e) {
System.out.println("Error " + e);
} /* End catch. */
}
public void getFileName()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter file name please.");
fname = in.nextLine();
System.out.println("You entered "+fname);
}
}
This is the LinkedListNode class:
public class LinkedListNode
{
private String data;
private LinkedListNode next;
public LinkedListNode(String data)
{
this.data = data;
this.next = null;
}
public String getData()
{
return data;
}
public LinkedListNode getNext()
{
return next;
}
public void setNext(LinkedListNode n)
{
next = n;
}
}
And finally the LinkedList class that has the main method:
import java.util.Scanner;
public class LinkedList {
public LinkedListNode head;
public static void main(String[] args) {
fileIn f = new fileIn();
LinkedList l = new LinkedList();
System.out.println(l.showList());
}
public LinkedList() {
this.head = null;
}
public void insertBack(String data){
if(head == null){
head = new LinkedListNode(data);
}else{
LinkedListNode newNode = new LinkedListNode(data);
LinkedListNode current = head;
while(current.getNext() != null){
current = current.getNext();
}
current.setNext(newNode);
}
}
public String showList(){
int i = 0;
String retStr = "List nodes:\n";
LinkedListNode current = head;
while(current != null){
i++;
retStr += "Node " + i + ": " + current.getData() + "\n";
current = current.getNext();
}
return retStr;
}
}
The problem is that you create the LinkedList in your fileIn.
But then you do not export it:
fileIn f = new fileIn();
LinkedList l = new LinkedList();
What you need is something like this:
fileIn f = new fileIn();
LinkedList l = f.readFileContents(String filename, new LinkedList());
Change the method to use the LinkedList you created and then populate it. So the fileIn class might look like something like this:
public class fileIn {
...
public void readFileContents(String fileName, LinkedList) {
// fill linked list
}
...
}

Categories