I implemented a linkedList in Java and now I am working on a new method toArray in order to sort the link list after. I am getting an error when I am trying to print each elements of the ArrayList Cannot resolve method 'toString(java.util.List)'
public class Node {
int value;
Node next;
}
public class LinkedList {
Node head;
public void toArray(LinkedList list){
List<Integer> temp = new ArrayList<>();
Node iterator = head;
while(iterator != null){
temp.add(iterator.value);
iterator = iterator.next;
}
temp.forEach(arr->System.out.println(Arrays.toString(temp)));
}
This expression is wrong:
System.out.println(Arrays.toString(temp))
Because temp is an ArrayList, not an Array. Try this:
System.out.println(temp)
By the way, you still have some errors in your code, this should fix them:
public void toArray() {
List<Integer> temp = new ArrayList<>();
Node iterator = head;
while (iterator != null) {
temp.add(iterator.value);
iterator = iterator.next;
}
temp.forEach(System.out::println);
}
The method Arrays.toString() needs an Array in argument.
You need transform you List an one Array calling the method: toArray().
Like this:
temp.forEach(arr->System.out.println(Arrays.toString(temp.toArray())));
Related
I was asked this question in an interview to clone the elements of linked list A into a new list. This was my approach but I was rejected. I did get it right but I am not sure why the interviewer didn't like my approach. Any tips/advise to what I could have done better? List A has elements [10,12,11,4,5,6] let's assume.
public class CopyLinkedListElements {
public static void main(String[] args) {
LinkedList linkedList = new LinkedList();
linkedList.head = new Node(10);
linkedList.head.next = new Node(12);
linkedList.head.next.next = new Node(11);
linkedList.head.next.next.next = new Node(4);
linkedList.head.next.next.next.next = new Node(5);
linkedList.head.next.next.next.next.next = new Node(6);
cloneOrgList(linkedList.head);
}
public static void cloneOrgList(Node head) {
Node current = head;
Node newHead = new Node(current.data);
Node prev = newHead;
System.out.println(prev.data);
while(current != null && current.next != null) {
current = current.next;
Node newNode = new Node(current.data);
prev.next = newNode;
prev = newNode;
System.out.println(prev.data);
}
}
}
In addition to what was mentioned about return values, the loop is a bit messy. It can be improved like this:
public static Node cloneLinkedList(Node head) {
Node oldCurrent = head;
Node newHead = new Node(oldCurrent.data);
Node newCurrent = newHead;
while ((oldCurrent = oldCurrent.next) != null) {
newCurrent.next = new Node(oldCurrent.data);
newCurrent = newCurrent.next;
}
return newHead;
}
If the interviewer used the word "clone" and not "copy" he or she might have wanted to know if you know how to properly clone objects in Java. IF that was the case, you needed to create a cloneable class. The basic recipe for this is to implement the Cloneable marker interface and override Object's clone method.
public class MyClass implements Cloneable {
// Details of MyClass omitted
// Because Java supports covariant return types, the return type
// for the overridden clone method is the same as the class (i.e. MyClass)
// Also, the method needs to be made public instead of protected.
#Override
public MyClass clone() {
try {
return (MyClass) super.clone();
} catch (CloneNotSupportedException e) {
throw new AssertionError("Something went wrong. This isn't supposed to happen");
}
}
}
If he or she just wanted a copy, an approach like the one you showed should've been OK, except for what has been already mentioned: Your function failed to return the copy. So, in essence, the method is useless.
Lastly, since your original post stated "clone the elements of linked list", you could've done call Linked List clone method
LinkedList<SomeClass> original = new LinkedList<>();
...
LinkedList<SomeClass> clone = (LinkedList<SomeClass>) original.clone();
Again, if the interviewer wanted you to copy the contents, you could've done one of the following:
Collections.copy(dest, source)
dest.addAll(source)
List<String> dest = source.stream().collect(Collectors.toList());
Lastly, the third alternative was the interviewer wanted you to get into cloning vs copying objects in Java, in which case you would've demonstrated both. In the future, ask the interviewer to clarify and restate the question in your own words to get confirmation that you understood the question correctly BEFORE you jump into coding. From your code, it is clear you misunderstood the interviewer.
You need to clone the list such that new references and values are returned. This is not happening in the cloneOrgList method. It doesn't return anything and the scope of the node it operates on is limited to the method itself.
You need to do something like
public LinkedList cloneOrgList(LinkedList orig) {
Node origCurr = orig.head;
LinkedList copy = new LinkedList();
Node newCurr = new Node(origCurr.data);
copy.head = newCurr;
while (origCurr.next != null) {
origCurr = origCurr.next;
newCurr.next = new Node(origCurr.data);
newCurr = newCurr.next;
}
return copy;
}
I think He was expecting to use the clone() method.
Please have a look at the official doc.Javadoc
Sample Code:
package com.raushan.testmind;
import java.util.LinkedList;
public class TestMain {
public static void main(String args[]) {
// Creating an empty LinkedList
LinkedList<Integer> list = new LinkedList<Integer>();
// Use add() method to add elements in the list
list.add(10);
list.add(12);
list.add(11);
list.add(4);
list.add(5);
list.add(6);
// Displaying the list
System.out.println("First LinkedList:" + list);
// Creating another linked list and copying
LinkedList sec_list = new LinkedList();
sec_list = (LinkedList) list.clone();
// Displaying the other linked list
System.out.println("Second LinkedList is:" + sec_list);
}
}
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
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);
}
}
I am trying to implement a linked list in java using arrays as the underlying structure. However, I am not sure how to do insert an element in the array after an element and shift the array down by one
class linkedList{
char data[];
int next;
//constructor
public linkedList(int MAX){
data = new char[MAX];
}
public void insertFirst(char d){
if(data[next]==0){
data[next] = d;
next++;
}
else{
System.out.println("list is full");
}
}
public void insertAfter (char after ,char value){
next=0;
while(data[next] !=after){
next++;
}
char temp = data[next+1];
data[next+1] = value;
}
public void printList(){
for(int i=0;i<data.length;i++){
System.out.print(data[i]);
}
}
}
public class myLinkedList {
public static void main(String args[]) {
linkedList list = new linkedList(9);
list.insertFirst('T');
list.insertFirst('H');
list.insertFirst('L');
list.insertAfter('H', 'z');
list.printList();
}
}
Also would this be considered a linked list?
This is not a linked list. What you have is similar to an ArrayList, in that an array is used as the underlying data structure. A linked list is composed of a series of nodes, with each node linked to the next. The linked list is traversed by calling something like node.next() on the current node until the target or the end of the list is reached.
If you want to insert another element into your list structure after reaching the size limit, you will need to create a new array, copy the contents of the old array over, and insert the new element into the array. You can use System.arraycopy() to perform the copying or to shift items within the array.
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?