Trying to populate a singly linked list - java

So I have a singly linked list in java
public class ListNode {
int val;
ListNode next;
ListNode(int x){
val = x;
}
}
Now what I am trying to do, is populate the list with the String number = "213214" which is essentially just a number. Now each node will be a single digit from that number.
This is what I have currently.
int firstnode = Integer.parseInt(String.valueOf(m.charAt(0)));
ListNode root = new ListNode(firstnode);
for(int i = 1; i<m.length(); ++i) {
while (root.next == null) {
root.next = new ListNode(Integer.parseInt(String.valueOf(m.charAt(i))));
}
root = root.next;
}
So I am trying to make it so that
root(2)->node(1)->node(3)->node(2)->node(1)->node(4)->ListEND
Any ideas?

So as I checked, your code is working fine. just that you lost the root node(head) when you change the root variable for inserting a new ListNode. Use a temp varaiable for that. Following is the altered code.
public static void main(String[] args) {
String m = "213214";
int firstnode = Integer.parseInt(String.valueOf(m.charAt(0)));
ListNode root = new ListNode(firstnode);
ListNode temp = root;
for (int i = 1; i < m.length(); ++i) {
while (temp.next == null) {
temp.next = new ListNode(Integer.parseInt(String.valueOf(m.charAt(i))));
}
temp = temp.next;
}
temp = root;
while (temp != null) {
System.out.print("->" + temp.val);
temp=temp.next;
}
}
Also you don't need a while loop inside the for loop. It always runs just once.

Try this way
public class SingleLinkedList {
LinkedList root = null;
public static void main(String[] args) {
SingleLinkedList sll = new SingleLinkedList();
sll.root = new LinkedList(1);
sll.root.next = new LinkedList(2);
sll.root.next.next = new LinkedList(3);
sll.root.next.next.next = new LinkedList(4);
sll.root.next.next.next.next = new LinkedList(5);
while (sll.root != null){
System.out.println("sll.root.value = " + sll.root.value);
sll.root = sll.root.next;
}
}
}
class LinkedList{
int value;
LinkedList next;
LinkedList(int data){
value = data;
next = null;
}
}

I think this should work for you. Since root is assigned to new root element, you cannot print. Keep the root element reference and use it for print logic
ListNode root = new ListNode(firstnode);
ListNode printRoot = root;
for (int i = 1; i < m.length(); i++) {
if (root.next == null) {
root.next = new ListNode(Integer.parseInt(String.valueOf(m.charAt(i))));
root = root.next;
}
}
while(printRoot !=null) {
System.out.println(printRoot.val);
printRoot = printRoot.next;
}

Since there is a root node. Following codes works.
import java.util.*;
import java.util.stream.*;
public class ListNode {
public static void main(final String... args) {
final ListNode root = new ListNode(0);
"213214".chars()
.map(Character::getNumericValue)
.mapToObj(ListNode::new)
.reduce(root, (n1, n2) -> {
n1.next = n2;
return n2;
});
;
System.out.println(root);
}
ListNode(final int value) {
super();
this.value = value;
}
#Override
public String toString() {
return super.toString() + "{"
+ "value=" + value
+ ",next=" + next
+ "}";
}
private int value;
private ListNode next;
}

Related

How can I add an item to the end the a Linked List?

I am working on a project for my Data Structures class that asks me to write a class to implement a linked list of ints.
Use an inner class for the Node.
Include the methods below.
Write a tester to enable you to test all of the methods with whatever data you want in any order.
I have to create a method called "public void addToBack(int item)". This method is meant to "Add an Item to the end of the list" I have my code for this method down below. When I execute this method my list becomes empty. Does someone know what I did wrong and how to fix it?
import java.util.Random;
import java.util.Scanner;
public class LinkedListOfInts {
Node head;
Node tail;
private class Node {
int value;
Node nextNode;
public Node(int value, Node nextNode) {
this.value = value;
this.nextNode = nextNode;
}
}
public LinkedListOfInts(LinkedListOfInts other) {
Node tail = null;
for (Node n = other.head; n != null; n = n.nextNode) {
if (tail == null)
this.head = tail = new Node(n.value, null);
else {
tail.nextNode = new Node(n.value, null);
tail = tail.nextNode;
}
}
}
public LinkedListOfInts(int[] other) {
Node[] nodes = new Node[other.length];
for (int index = 0; index < other.length; index++) {
nodes[index] = new Node(other[index], null);
if (index > 0) {
nodes[index - 1].nextNode = nodes[index];
}
}
head = nodes[0];
}
public LinkedListOfInts(int N, int low, int high) {
Random random = new Random();
for (int i = 0; i < N; i++)
this.addToFront(random.nextInt(high - low) + low);
}
public void addToFront(int x) {
head = new Node(x, head);
}
public void addToBack(int x) {
if (head == null) {
head = new Node(x, head);
return;
}
tail = head;
while (tail.nextNode != null) {
tail = tail.nextNode;
}
tail.nextNode = new Node(x, tail);
}
public String toString() {
String result = "";
for (Node ptr = head; ptr != null; ptr = ptr.nextNode) {
if (!result.isEmpty()) {
result += ", ";
}
result += ptr.value;
}
return "[" + result + "]";
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
LinkedListOfInts list = new LinkedListOfInts(10, 1, 20);
boolean done = false;
while (!done) {
System.out.println("1. Add to Back");
System.out.println("2. toString");
switch (input.nextInt()) {
case 1:
System.out.println("Add an Item to the Back of a List.");
list.addToBack(input.nextInt());
break;
case 2:
System.out.println("toString");
System.out.println(list.toString());
break;
}
}
}
}
When you add to the tail the nextNode should point to null
tail.nextNode = new Node(x, null);
At the moment you are having an endless loop

How to get length and isEmpty methods as a return value to get method used for my Circular Linked List?

There is a problem I came across when I have seen two methods never used in the Linked List:
New Update!!!
public class CircularLinkedList {
private ListNode last;
private int length;
private static class ListNode {
private ListNode next;
private final int data;
public ListNode(int data) {
this.data = data;
}
}
public static void main(String[] args) {
CircularLinkedList cll = new CircularLinkedList();
CircularLinkedList insertBeg = new CircularLinkedList();
CircularLinkedList insertEnd = new CircularLinkedList();
System.out.println("creating a traverse list");
cll.createCircularLinkedList();
cll.display();
System.out.println("Insert Starting Node");
insertBeg.insertFirst(10);
insertBeg.insertFirst(15);
insertBeg.insertFirst(20);
insertBeg.insertFirst(25);
insertBeg.display();
insertEnd.insertLast(25);
insertEnd.insertLast(20);
insertEnd.insertLast(15);
insertEnd.insertLast(10);
// I just need to print out the isEmpty amd length
System.out.println(insertEnd.isEmpty());
System.out.println(insertEnd.length());
insertEnd.display();
}
public CircularLinkedList () {
last = null;
length = 0;
}
public void display() {
if(last == null) {
return;
}
ListNode first = last.next;
while(first != last) {
System.out.print(first.data + " --> ");
first = first.next;
}
System.out.println(first.data);
}
public void insertFirst(int data) {
ListNode temp = new ListNode(data);
if (last == null) {
last = temp;
} else {
temp.next = last.next;
}
last.next = temp;
length++;
}
public void insertLast(int data) {
ListNode temp = new ListNode(data);
if (last == null) {
last = temp;
last.next = temp;
} else {
temp.next = last.next;
last.next = temp;
last = temp;
}
length++;
}
public int length () {
ListNode temp = last.next;
int count = length;
while (temp != last) {
count++;
temp = temp.next;
}
return count;
}
public boolean isEmpty(){
return length == 0;
}
public void createCircularLinkedList() {
ListNode first = new ListNode(1);
ListNode second = new ListNode(5);
ListNode third = new ListNode(10);
ListNode fourth = new ListNode(15);
first.next = second;
second.next = third;
third.next = fourth;
fourth.next = first;
last = fourth;
}
}
I try to fix this problem for my Circular Linked List by trying to void the method. However, I want to test and see if I can get the method working by printing out the value for the length and isEmpty. Is there a way to work around this issue on IntelliJ?
Return value of the method is never used for both length and isEmpty
It's just a warning, that some other code is calling the method but ignoring the result.
The solution is to fix that other code.

Binary Tree Output

Hi how do I make the program output the sum of the numbers instead of giving them out seperately?
public class Tree {
private Node root;
public int sum;
public class Node{
private Node left;
private Node right;
private int val;
public Node(int data) {
this.val = data;
}
}
public void createTree() {
Node first = new Node(7);
Node second = new Node(2);
Node third = new Node(6);
Node fourth = new Node(4);
root = first;
first.left = second;
first.right = third;
second.left = fourth;
}
public void Sum(Node root) {
if(root == null) {
return;
}
System.out.print(root.val + " ");
Sum(root.left);
Sum(root.right);
}
public static void main(String[] args) {
Tree tree = new Tree();
tree.createTree();
tree.Sum(tree.root);
}
}
Current output is 7 2 6 4 but I want them to be added into a sum in the System outprint if possible. I couldnt get it to work for some reason so maybe someone can help me with it.
You can recursively get the sum by doing the following:
public double sum(Node root) {
double leftSum, rightSum, totalSum;
if (root == null) {
totalSum = 0;
return totalSum;
}else {
leftSum = sum(root.left);
rightSum = sum(root.right);
totalSum = root.val + leftSum + rightSum;
return totalSum;
}
}
You need to return the sum of the left and right nodes and print the return value from main(). Also, there's no need for sum() to be an intance method since you're passing in root:
public static int sum(Node root) {
if(root == null) {
return 0;
}
return sum(root.left) + sum(root.right);
}
public static void main(String[] args) {
Tree tree = new Tree();
tree.createTree();
System.out.println(sum(tree.root));
}

How can I reverse this linked list starting from nth element to the end

So I'm trying to construct a method in Java that when called will take as the parameter how many elements at the end of the LinkedList will be reversed.
So, if I have
{hat cat bat mat}
and I input 2 as my parameters, then the last 2 elements will be reversed like this
{hat cat mat bat}
Here is what I have tried:
public void reverseLastFew(int howMany)
{
int s = size();
LinkedListIterator iter1 = new LinkedListIterator();
LinkedListIterator iter2 = new LinkedListIterator();
for (int i=0;i<s-howMany;i++)
{
iter1.next();
}
for (int i = 0;i<s;i++)
{
iter2.next();
}
Object temp = null;
while (iter2.hasNext())
{
temp = iter2.next();
}
iter2.remove();
iter1.add(temp);
}
I have a solution to a similar question:
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given "1"->"2"->"3"->"4"->"5"->NULL, m = 2 and n = 4,
return "1"->"4"->"3"->"2"->"5"->NULL.
Solution:
/**
* Definition for singly-linked list.
* public class ListNode {
* String val;
* ListNode next;
* ListNode(String x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if (head==null) {
return null;
}
ListNode dummy = new ListNode(" ");
dummy.next = head;
head = dummy;
for (int i=1; i<m; i++) {
head = head.next;
}
ListNode pre = head;
ListNode start = head.next;
ListNode end = start;
ListNode post = start.next;
for (int i=m; i<n; i++) {
if (post==null) {
return null;
}
ListNode temp = post.next;
post.next = end;
end = post;
post = temp;
}
start.next = post;
pre.next = end;
return dummy.next;
}
}
So, you can calculate m and n with what you have, or modify this solution to solve your question directly. Anyway, this in-place and one-pass solution is really nice.
you can try this code..........
import java.util.LinkedList;
public class LinkListTry {
public LinkedList<String> linkedlist;
public LinkListTry(){
linkedlist = new LinkedList<String>();
}
public void insertElement(String element){
linkedlist.add(element);
}
public void printListElement(){
System.out.println(linkedlist);
}
public void reverseLastFewElement(int howmany){
LinkedList<String> temp = new LinkedList<String>();
while(howmany > 0){
String str = linkedlist.removeLast();
temp.add(str);
--howmany;
}
linkedlist.addAll(temp);
}
}
public class LinkedListTryMain {
public static void main(String[] args){
LinkListTry test = new LinkListTry();
test.insertElement("hat");
test.insertElement("cat");
test.insertElement("bat");
test.insertElement("mat");
test.printListElement();
test.reverseLastFewElement(2);
test.printListElement();
}
}

Unit Test for 'Merge Sort on doubly linked list'

Need to create unit test please help
When i created unit test, it shows error "No parameters allowed in test"
package MergeDoublyLL;
import java.util.ArrayList;
import java.util.Iterator;
public class doublell {
static Node head;
static class Node {
int data;
Node next, prev;
Node(int d) {
data = d;
next = prev = null;
}
}
Node split(Node head) {
Node fast = head, slow = head;
while (fast.next != null && fast.next.next != null) {
fast = fast.next.next;
slow = slow.next;
}
Node temp = slow.next;
slow.next = null;
return temp;
}
Node mergeSort(Node node) {
if (node == null || node.next == null) {
return node;
}
Node second = split(node);
node = mergeSort(node);
second = mergeSort(second);
return merge(node, second);
}
Node merge(Node first, Node second) {
if (first == null) {
return second;
}
if (second == null) {
return first;
}
if (first.data < second.data) {
first.next = merge(first.next, second);
first.next.prev = first;
first.prev = null;
return first;
} else {
second.next = merge(first, second.next);
second.next.prev = second;
second.prev = null;
return second;
}
}
int[] print(Node node) {
int a;
ArrayList<Integer> al = new ArrayList<Integer>();
Node temp = node;
System.out.println("Forward Traversal using next pointer");
while (temp != null) {
a=(temp.data);
al.add(a);
temp = temp.next;
}
int[] ret = new int[al.size()];
Iterator<Integer> iterator = al.iterator();
for (int i = 0; i < ret.length; i++)
{
ret[i] = iterator.next().intValue();
}
return ret;
}
public static void main(String[] args) {
doublell list = new doublell();
doublell.head = new Node(10);
doublell.head.next = new Node(30);
doublell.head.next.next = new Node(3);
doublell.head.next.next.next = new Node(4);
doublell.head.next.next.next.next = new Node(20);
doublell.head.next.next.next.next.next = new Node(5);
Node node;
node=head;
node = list.mergeSort(head);
System.out.println("Linked list after sorting :");
int[] result =list.print(node);
for (int j=0; j<result.length;j++)
System.out.print(result[j]);
}
}
Unit Test:
// Unit Test
package MergeDoublyLL;
import static org.junit.Assert.assertArrayEquals;
import org.junit.Test;
import MergeDoublyLL.doublell.Node;
public class testdoublell {
#Test
public void test(Node head) {
doublell list = new doublell();
doublell.head = new Node(10);
doublell.head.next = new Node(30);
doublell.head.next.next = new Node(3);
doublell.head.next.next.next = new Node(4);
doublell.head.next.next.next.next = new Node(20);
doublell.head.next.next.next.next.next = new Node(5);
Node node=head;
node = list.mergeSort(head);
int result[] =list.print(node);
int expectedArray[] = {3,4,5,10,20,30};
assertArrayEquals(expectedArray, result);
}
}
Unit test should test a single unit of code independently from everything else. You are passing in an argument to your test:
#Test
public void test(Node head) {
Instead just create the head node inside the test and don't have arguments:
#Test
public void test() {

Categories