Why does reversing my linkedlist not work as expected? - java

Below is linked list program, I am trying to reverse the linked list by k- nodes. k is the input provided by the user. But the issue is below logic only returns first three nodes in reverse order.
package p;
import java.util.Scanner;
public class LinkedListDemoReverseKNode {
class MyList {
public int info;
public MyList link;
public MyList(){
this.link = null;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
MyList s = new MyList();
System.out.println("enter value :");
s.info = sc.nextInt();
Character ch = null;
MyList t = s;
MyList commonNode = null;
while (true) {
System.out.println("to create node press Y else N ");
ch = sc.next().charAt(0);
if (ch == 'n' || ch == 'N') {
break;
}
s.link = new MyList();
System.out.println("enter value for the node :");
s.link.info = sc.nextInt();
s = s.link;
}
// Reverse the linked list k-node :
s = t;
LinkedListDemoReverseKNode linkedListDemo3 = new LinkedListDemoReverseKNode();
MyList head = linkedListDemo3.reverseLinkedListKNode(s, 3);
while (head != null) {
System.out.println("info :: " + head.info);
head = head.link;
}
}
private MyList reverseLinkedListKNode(MyList head, int k) {
MyList s = head;
MyList prev = null;
MyList next = null;
int count = 0;
while (count < k && s != null) {
next = s.link;
s.link = prev;
prev = s;
s = next;
count++;
}
if (next != null)
s.link = reverseLinkedListKNode(next, k);
return prev;
}
}

// Reverse the linked list k-node :
s = t;
LinkedListDemoReverseKNode linkedListDemo3 = new LinkedListDemoReverseKNode();
MyList head = linkedListDemo3.reverseLinkedListKNode(s, 3);
while (head != null) {
System.out.println("info :: " + head.info);
head = head.link;
In this line of code where it says:
MyList head = linkedlistDemo3.reverselinkedlistNode(s,3)
Try changing where it says (s, 3)

If you look at this part of your code MyList head = linkedListDemo3.reverseLinkedListKNode(s, 3); you are telling it to reverse the three first nodes in your linked list.
The method asks for number of k nodes to be reversed:
private MyList reverseLinkedListKNode(MyList head, int k)
You could set k to the total nodes in the list to reverse all nodes, or to any number of nodes to reverse.
Good luck.

You can simply use Collections.reverse...

Related

java code merge two listed llink arrays and order it in decreasing order to new array

I'm trying to have the user input integers for first linked list and second linked list then merge them into a new array in decreasing order. The problem is when it print out the result it identify two digits number as one number and ordering it wrong.
Example:
enter first sentence:
1 8 0 4
enter second sentence:
3 2 9 10
result:
9 8 4 3 2 10 1 0
The problem is
it counted 10 as 1
The desired result
10 9 8 4 3 2 1 0
Here my codes and classes
package homework;
import static homework.Cipher.decode;
import static homework.Cipher.encode;
import java.util.Scanner;
public class HOMEWORK {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x = 0;
while (x != 5) {
System.out.println("-_-_-_-_-MENU-_-_-_-_-\n1-Encrypt Text"
+ "\n2-Decrypt Text"
+ "\n3-Merge two sorted list in decreasing order"
+ "\n4- Reverse Linked List Recursively "
+ "\n5- Exit ");
System.out.println("Please enter your choice: ");
x = input.nextInt();
input.nextLine();
switch (x) {
case 1:
System.out.println("Please enter Line to encode: ");
String plaintext = input.nextLine();
System.out.println("Please enter Shift Number:");
int number = input.nextInt();
input.nextLine();
String encoded = encode(plaintext, number);
System.out.println("Result:");
System.out.println(encoded);
break;
case 2:
System.out.println("Please enter Line to decode: ");
String code = input.nextLine();
System.out.println("Please enter Shift Number:");
int number1 = input.nextInt();
input.nextLine();
System.out.println("Result:");
System.out.println(decode(code, number1));
break;
case 3:
Merge list1 = new Merge();
Merge list2 = new Merge();
System.out.println("Enter first scentence :");
String[] string1 = input.nextLine().split(" ");
System.out.println("Enter second scentence :");
String[] string2 = input.nextLine().split(" ");
for (int i = 0; i < string1.length; i++) {
list1.insert(string1[i]);
}
for (int i = 0; i < string2.length; i++) {
list2.insert(string2[i]);
}
Merge merged = list1.merge(list1, list2);
System.out.println("Result ");
merged.Display();
System.out.println();
break;
case 4:
SinglyLinkedList LL = new SinglyLinkedList();
System.out.println("Enter scentence to reverse :");
String[] string = input.nextLine().split(" ");
for (int i = 0; i < string.length; i++) {
LL.addLast(string[i]);
}
System.out.println("REVERSED");
System.out.println(LL.reverse());
break;
case 5:
default:
System.out.println(" Goodbye ");
}
}
}
}
My Merge class
package homework;
public class Merge {
public Node head = null; // head node of the list (or null if empty)
// access methods
int size = 0;
// update methods
public void addFirst(String e) { // adds data e to the front of the list
head = new Node(e, head);// create and link a new node
size++;
}
public String deleteFirst() {
if (size == 0) {
return "";
}
String remo = head.element;
head = head.next;
size--;
return remo;
}
public void insert(String element) {
if (head == null || head.element.compareTo(element) >= 0) {
addFirst(element);
} else {
Node p = head;
Node c = p.next;
while (c != null && c.element.compareTo(element) <= 0) {
p = c;
c = c.next;
}
Node newest = new Node(element, c); // node will eventually be the tail
p.next = newest;
}
}
public void Display() {
Node N = head;
while (N != null) {
System.out.print(N.element + " ");
N = N.next;
}
}
public Merge merge(Merge list1, Merge list2) {
Merge merged = new Merge();
Node head1 = list1.head;
Node head2 = list2.head;
if (head1 == null) {
return list2;
}
if (head2 == null) {
return list1;
}
merged.head = null;
if (head1.element.compareTo(head2.element) <= 0) {
merged.head = head1;
head1 = head1.next;
} else {
merged.head = head2;
head2 = head2.next;
}
Node mergedTail = merged.head;
while (head1 != null && head2 != null) {
Node temp = null;
if (head1.element.compareTo(head2.element) <= 0) {
temp = head1;
head1 = head1.next;
} else {
temp = head2;
head2 = head2.next;
}
mergedTail.next = temp;
mergedTail = temp;
}
if (head1 != null) {
mergedTail.next = head1;
} else if (head2 != null) {
mergedTail.next = head2;
}
Node p = null;
Node c = merged.head;
Node next = null;
while (c != null) {
next = c.next;
c.next = p;
p = c;
c = next;
}
merged.head = p;
return merged;
}
public static class Node {
private String element;
private Node next;
// reference to the data stored at this node // reference to the subsequent node in the list
public Node(String e, Node n) {
element = e;
next = n;
}
}
}
I tried to change them into integers instead of a string but it won't work and only give me errors everywhere.
Return is correct:
3 2 9 10 => 9 3 2 10
1 8 0 4 => 8 4 1 0
result: 9 8 4 3 2 10 1 0
Just missing the sorting

Deleting N nodes after M nodes in a Singly Linked List

Given a linked list, delete N nodes after skipping M nodes of a linked list until the last of the linked list
This is the Java program I wrote to solve this problem. For certain large test cases it's showing error,
"Exception in thread "main" java.lang.NullPointerException: Cannot assign field "next" because "" is null
at SinglyLinkedList.deleteNNodesAfterEveryMNodes(DeleteNNodesAfterMNodesOfALinkedList.java:88)
at DeleteNNodesAfterMNodesOfALinkedList.main(DeleteNNodesAfterMNodesOfALinkedList.java:127)"
import java.io.*;
import java.util.*;
class Link
{
public int data;
public Link next;
public Link(int d)
{
data = d;
}
public void displayLink()
{
System.out.print(data + " ");
}
}
class SinglyLinkedList
{
public Link first;
public SinglyLinkedList()
{
first = null;
}
public boolean isEmpty()
{
return(first == null);
}
public void insertLast(int d)
{
Link nl = new Link(d);
if(isEmpty())
{
first = nl;
}
else
{
Link curr = first;
while(curr.next != null)
{
curr = curr.next;
}
curr.next = nl;
}
}
public void displayList()
{
Link curr = first;
while(curr != null)
{
curr.displayLink();
curr = curr.next;
}
}
public void deleteNNodesAfterEveryMNodes(int N, int M)
{
Link curr1=first, curr2=first;
int n=N+M, m=M;
while(curr1!=null && curr1.next!=null)
{
while(curr2!=null && n!=0)
{
if(m != 1)
{
curr1 = curr1.next;
m--;
}
curr2 = curr2.next;
n--;
}
curr1.next = curr2;
m = M;
n = N+M;
curr1 = curr2;
}
}
}
class DeleteNNodesAfterMNodesOfALinkedList
{
public static void main(String st[])
{
Scanner sc = new Scanner(System.in);
SinglyLinkedList sll = new SinglyLinkedList();
int count, d, N, M;
System.out.println("Enter the number of integers you want to store in the singly linked list: ");
count = sc.nextInt();
System.out.println("\nEnter the " + count + " integers: ");
for(int i=0; i<count; i++)
{
d = sc.nextInt();
sll.insertLast(d);
}
System.out.println("\nThe singly linked list is: ");
sll.displayList();
System.out.println("\n\nEnter the value of 'M', the number of nodes to be skipped: ");
M = sc.nextInt();
System.out.println("\nEnter the value of 'N', the number of nodes now to be deleted: ");
N = sc.nextInt();
sll.deleteNNodesAfterEveryMNodes(N, M);
System.out.println("\nThe resultant singly linked list is: ");
sll.displayList();
}
}
I can't figure out what went wrong and how is assigning curr1.next = curr2; is of any issue at line 127
You can either try to put an additional check of curr1!=null in the second while loop or simplify the problem.
Simplifying the problem can be done by:
Using a for loop (m number of times) to traverse the list.
Using another for loop (n number of times) to call a piece of code that deletes the nodes one by one.
Also check for edge conditions i.e. if m + n < size and so on.

Getting an error when creating two separate linkedlists in Java

I will do the addition multiplication and print operations of two separate polynomials that I will get from the user. However, when creating two linkedlists in the main class, the nodes that I added to the first linkedlist are replaced by the nodes that I added to the second linkedlist. How can I solve this?
public class Main {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int coefficient, degree;
int coef, deg;
MyLinkedList ml, ml2;
ml = new MyLinkedList();
System.out.println("Enter the coefficient and power of the first polynomial. Type 0 at the end: ");
coefficient = scn.nextInt();
degree = scn.nextInt();
ml.insertLast(coefficient, degree);
//System.out.println(ml.toString());
while (true) {
if (coefficient != 0) {
coefficient = scn.nextInt();
degree = scn.nextInt();
ml.insertLast(coefficient, degree);
} else {
break;
}
}
//System.out.println(ml.toString());
ml2 = new MyLinkedList();
System.out.println("Enter the coefficient and power of the second polynomial. Type 0 at the end: ");
coef = scn.nextInt();
deg = scn.nextInt();
ml2.insertLast(coef, deg);
//System.out.println(ml2.toString());
while (true) {
if (coef != 0) {
coef = scn.nextInt();
deg = scn.nextInt();
ml2.insertLast(coef, deg);
} else {
break;
}
}
}
}
public class MyLinkedList {
static Node first;
static Node last;
static int size = 0;
public MyLinkedList() {
first = null;
last = null;
size = 0;
}
public static void insertLast(int x,int y) {
Node newNode = new Node(x,y);
if (first == null) {
first = newNode;
last = newNode;
} else {
last.next = newNode;
last = newNode;
}
size++;
}
public String toString() {
Node tmp = first;
String str = "";
while (tmp != null) {
str += tmp.coef + "x^"+ tmp.power + "->";
tmp = tmp.next;
}
return str;
}
}
Inside your LinkedList class you declare your Nodes "first" and "last" as static. This means that both LinkedLists share the same first and last. You wont be able to have a separate linked list if they remain static.

Linked List User Input

I am trying to make a linked list which will take input from user that how many number he wants to make the linked list not using the built in LinkedList function. but if the user input a negative number it will give message the user to input a positive number. I have done the code for user input but finding very difficulty for other parts-negative input and linking the numbers.can anyone please give me these parts of codes.
import java.io.*;
import java.util.Scanner;
class MyList{
public MyList firstLink,lastLink;
int info,size;
MyList link;
private MyList next;
MyList(){
this.link=null;
firstLink = null;
lastLink=null;
}
public boolean isEmpty(){
return(firstLink == null);
}
public void showMyList() {
MyList currentLink = firstLink;
System.out.print("List: ");
while(currentLink != null) {
currentLink.showMyList();
currentLink = currentLink.lastLink;
}
System.out.println("");
}
}
public class MyLinkedList {
public static void main(String[] args){
MyList newMyList=new MyList();
Scanner userInput= new Scanner(System.in);
int userInputNumber;
System.out.println("Enter Total Data");
userInputNumber = userInput.nextInt();
int i=1;
while(i<=userInputNumber){
System.out.println("Enter Data "+ i +":");
i++;
newMyList.info=userInput.nextInt();
}
if(newMyList.firstLink!=null){
newMyList=newMyList.firstLink;
newMyList=newMyList.lastLink;
newMyList.firstLink=newMyList.firstLink.link;
}
}
}
This could help you understand Linked Lists:
LinkedList in wikipedia
A LinkedList consists of Nodes. A node could look like this:
class Node {
Node previousNode, nextNode;
int value;
public Node getLastNode() {
// traverse nextNode till it is null.. return the Node before.
}
}
Make a method for reading the user input, which returns the number entered.
private int getUserInput() {
int result = -1;
Scanner userInput= new Scanner(System.in);
while ( result < 0) {
result = userInput.nextInt();
}
return result;
}
After that you can create your LinkedList by creating Nodes as much as needed.
Node myLinkedList = new Node();
myLinkedList.value = 0;
for (int i = 1; i < getUserInputResult; i++) {
var newNode = new Node();
newNode.value = i;
// concat new Node to last Node in List;
var lastNodeInList = myLinkedList.getLastNode();
lastNodeInList .NextNode = newNode;
newNode.previousNode = lastNodeInList;
}

Unresolved compilation error

Here's my code for insertion of a node in a compressed suffix trie :
public class tree {
char a[] = new char[10];
a[0]='b';
a[1]='a';
a[2]='n';
a[3]='a';
a[4]='n';
a[5]='a';
a[6]=' ';
protected node root;
public tree() {
this.root = new node();
}
public void inorder(node n) {
if (n.getChildren().next != null) {
inorder(n.getChildren().next.getChild());
}
System.out.println(n.getStart() + n.getEnd());
if (n.getChildren().next.next != null) {
inorder(n.getChildren().next.next.getChild());
}
}
public void insert(node n, node r) {
while (n.getStart() != 6) {
if (r.getChildren().next == null) {
//when the tree is empty :
n.setParent(r);
n.getChildren().setNext(null);
link newn = new link();
newn.setNext(null);
newn.setChild(n);
r.getChildren().next = newn;
node newnode = n;
newnode.setStart(n.getStart() + 1);
insert(newnode, r);
}
else {
// count is the node where we begin checking for same letters :
node count = r.getChildren().next.getChild();
// l is the linked list containing children of the node :
link l = r.getChildren().next;
while ((a[count.getStart()] != a[n.getStart()])
|| (l.next != null)) {
l = l.next;
count = l.getChild();
}
// create a new link node corresponding to the node to be inserted
// only for the case when we reach the end of the list :
link h = new link();
h.setNext(null);
h.setChild(n);
// we have reached the end of the linked list :
if ((a[count.getStart()] != a[n.getStart()])
&& (l.next == null)) {
if (n.getStart() != n.getEnd()) {
l.setNext(h);
h.setNext(null);
h.setChild(n);
n.setParent(r);
n.getChildren().setNext(null);
node newnode = n;
newnode.setStart(n.getStart() + 1);
insert(newnode, r);
}
else {
l.setNext(h);
h.setNext(null);
h.setChild(n);
n.setParent(r);
n.getChildren().setNext(null);
node newnode = new node();
newnode.setStart(count.getStart() + 1);
newnode.setEnd(n.getEnd());
}
}
// if we have found an element whose characters
// match that of the node:
else {
link kids = count.getChildren();
int x = count.getStart();
int y = n.getStart();
int p = count.getEnd();
int q = n.getEnd();
int t1 = count.getStart();
int t2 = n.getStart();
int length = p - x + 1;
int same = 1;
while (a[x + 1] == a[y + 1]) {
x++;
y++;
same++;
}
int g = length - same;
//modifying the node r:
count.setStart(t1);
count.setEnd(x);
// creating the 2 new nodes to be inserted below count if
// count initially doesnt have any children :
node kid1 = new node();
kid1.setStart(x + 1);
kid1.setEnd(p);
kid1.getChildren().setNext(null);
node kid2 = new node();
kid2.setStart(y + 1);
kid2.setEnd(q);
// creating 2 new link nodes to be inserted in
// the children list of count :
link k1 = new link();
link k2 = new link();
k1.setChild(kid1);
k2.setChild(kid2);
k1.setNext(k2);
k2.setNext(null);
//changing relationships :
kid1.setChildren(kids);
kid1.setParent(count);
count.getChildren().next.setNext(k1);
while (kids.next != null) {
kids.next.getChild().setParent(kid1);
kids = kids.next;
}
insert(kid2, count);
}
}
}
}
public static void main(String[] args) {
tree t = new tree();
node banana = new node();
banana.setStart(0);
banana.setEnd(7);
banana.getChildren().setNext(null);
t.insert(banana, t.root);
//inorder(tree.root);
}
}
When I run it in Eclipse, it says that it has some unresolved compilation problem.
Can you please help me sort this out? Thanks.
You cannot have non-declarative statements in the class block.
a[0]='b';
a[1]='a';
...
All these array assignments belong in a method, constructor or static initializer block. Alternatively, if adjusting the length or your array, is an option you could simply use:
char a[] = "banana".toCharArray();

Categories