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();
Related
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 insertAt(int index, int item)". This method is meant to "Insert an item at position index, where index is passed to the method" I have my code for this method down below. When I execute this method nothing happens. The item that I try to add to a specific index never gets added. 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 insertAt(int index, int item) {
Node temp = head;
Node prev = null;
int i = 0;
for (Node ptr = head; ptr != null; ptr = ptr.nextNode) {
prev = temp;
temp = temp.nextNode;
i++;
}
if (index == i) {
Node newItem = new Node(item, null);
prev.nextNode = newItem;
newItem.nextNode = temp;
}
}
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. Insert At");
System.out.println("2. toString");
switch (input.nextInt()) {
case 1:
System.out.println("Insert an Item to a certain Index on the List");
list.insertAt(input.nextInt(), input.nextInt());
break;
case 2:
System.out.println("toString");
System.out.println(list.toString());
break;
}
}
}
}
There are a few issues, but you are most of the way there, you simply need to move the if statement if (index == i) {Node newItem... } inside of your 'for' loop like this:
public void insertAt(int index, int item) {
Node temp = head;
Node prev = null;
int i = 0;
for (Node ptr = head; ptr != null; ptr = ptr.nextNode) {
prev = temp;
//Make sure the next node is not null
if (temp.nextNode != null) {
temp = temp.nextNode;
}
//Move the if check here inside the for loop, but before i++
if (index == i) {
Node newItem = new Node(item, null);
prev.nextNode = newItem;
//Make sure the next node is not null
if (temp.nextNode != null) {
newItem.nextNode = temp;
}
}
//now advance the index after the above
i++;
}
}
Note that your code had an error, which has been fixed by checking that the next node is not null.
We can see the updated method works by inserting 999 after index 2:
1. Insert At
2. toString
1
Insert an Item to a certain Index on the List
2 999
1. Insert At
2. toString
2
toString
[5, 18, 8, 999, 11, 11, 1, 19, 3, 1, 10]
1. Insert At
2. toString
If you want the item to be inserted at index 2 instead, then adjust the order and put the if statement before prev = temp;
i'm trying to make a 11 x 11 matrix of nodes doubly linked nodes in Java but i have a problem, i linked the nodes to right, left and down node but when i try to link to the up node i just can't and when i try to get node.up for example, i got a null instead of getting an int(which i should get).
Anyway, here is my code hoping someone can help me. I guess the error may be in void linkUp().
public class CazadorPresa {
// node of linked list
static class Node {
int no;
Node right;
Node down;
Node left;
Node up;
int xpos,ypos;
public boolean hunter,prey,crossed,blocked;
};
// returns head pointer of linked list
// constructed from 2D matrix
static Node construct(int arr[][], int i, int j, int m, int n) {
// return if i or j is out of bounds
if (i > n - 1 || j > m - 1)
return null;
// create a new node for current i and j
// and recursively allocate its down and
// right pointers
Node temp = new Node();
temp.no = arr[i][j];
temp.xpos = j;
temp.ypos = i;
temp.blocked = false;
temp.crossed = false;
temp.hunter = false;
temp.prey = false;
temp.right = construct(arr, i, j + 1, m, n);
temp.down = construct(arr, i + 1, j, m, n);
return temp;
}
// utility function for displaying
// linked list data
static void display(Node head) {
// pointer to move right
Node Rp;
// pointer to move down
Node Dp = head;
// loop till node->down is not NULL
while (Dp != null) {
Rp = Dp;
// loop till node->right is not NULL
while (Rp != null) {
System.out.print(Rp.no + " ");
Rp = Rp.right;
}
System.out.println();
Dp = Dp.down;
}
}
// link left
static void linkLeft(Node head) {
Node Rp;
Node Dp = head;
Node auxL= head;
// loop till node->down is not NULL
while (Dp != null) {
Rp = Dp;
// loop till node->right is not NULL
while (Rp != null) {
if(Rp==Dp){
}else{
Rp.left = auxL;
auxL = Rp;
}
Rp = Rp.right;
}
Dp = Dp.down;
}
}
// link UP
static void linkUp(Node head) {
// pointer to move right
Node Rp;
// pointer to move down
Node Dp = head;
Node aux;
// loop till node->down is not NULL
while (Dp != null) {
Rp = Dp;
// loop till node->right is not NULL
while (Rp != null) {
aux = Rp.down;
if(aux==null){
}else{
aux.up = Rp;
}
Rp = Rp.right;
}
Dp = Dp.down;
}
}
static void hunter(Node head,int x, int y) {
Node arr,aba,izq,der;
boolean out = false;
// pointer to move right
Node Rp;
// pointer to move down
Node Dp = head;
// loop till node->down is not NULL
while (Dp != null) {
Rp = Dp;
// loop till node->right is not NULL
while (Rp != null) {
if(Rp.xpos==x-1 && Rp.ypos==y-1){
Rp.hunter = true;
arr=Rp.up;
if(arr==null){
System.out.println("No link up");
}else{
System.out.println(arr.no);
}
aba=Rp.down;
izq=Rp.left;
der=Rp.right;
System.out.println(" "+izq.no+" "+aba.no+" "+der.no);
out=true;
}
if(out==true){
break;
}
Rp = Rp.right;
}
if(out==true){
break;
}
Dp = Dp.down;
}
}
// driver program
public static void main(String args[]) {
// 2D matrix
int arr[][]= new int[11][11];
int no=1;
for(int i=0;i<11;i++){
for(int j=0;j<11;j++){
arr[i][j] = no;
no=no+1;
}
}
int m = 11, n = 11;
Node head = construct(arr, 0, 0, m, n);
linkUp(head);
linkLeft(head);
display(head);
System.out.println("I should get: 38 48 60 50 but i get: ");
hunter(head,5,5);
}
}
The problem is in the use of recursion to construct the grid of Nodes. When you do:
temp.right = construct(arr, i, j + 1, m, n);
temp.down = construct(arr, i + 1, j, m, n);
You're actually creating multiple versions of the grid, each one overwriting right and down linked Nodes that have already been created. For example, it should be the case that after construction, for a given node:
node.right.down == node.down.right
but given how the grid is constructed this will not be the case, which then causes problems when you come to try to link them up. You can see how bad the problem is by considering that for an 11x11 grid you should be creating 121 Nodes, but I checked and you're actually creating 705,431!
Fortunately the fix is fairly straightforward. Create a 2d array of Nodes and hook up them up directly:
public static void main(String args[]) {
// 2D matrix
Node arr[][]= new Node[11][11];
int m = 11, n = 11;
int no=1;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
arr[i][j] = new Node();
arr[i][j].no = no;
arr[i][j].xpos = j;
arr[i][j].ypos = i;
no=no+1;
}
}
for(int i=0; i<m; i++)
{
for(int j=0; j<n; j++)
{
arr[i][j].up = (i>0) ? arr[i-1][j] : null;
arr[i][j].left = (j>0) ? arr[i][j-1] : null;
arr[i][j].down = (i+1<m) ? arr[i+1][j] : null;
arr[i][j].right = (j+1<n) ? arr[i][j+1] : null;
}
}
Node head = arr[0][0];
display(head);
hunter(head,5,5);
}
}
Which produces:
38
48 60 50
Which I believe is the output you were expecting.
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...
public class doubleLinkedList {
class Node {
String value;
Node prev;
Node next;
Node(String val, Node p, Node n) {
value = val;
prev = p;
next = n;
}
Node(String val) {
value = val;
prev = null;
next = null;
}
}
Node first;
Node last;
public doubleLinkedList() {
first = null;
last = null;
}
public boolean isEmpty() {
if (first == null)
return true;
else
return false;
}
/**The size method returns the length of the linked list
* #return the number of element in the linked list
*/
public int size() {
int count = 0;
Node traverse = first;
while (traverse != null) {
count++;
traverse = traverse.next;
}
return count;
}
public void add(String element) {
if (isEmpty()) {
first = new Node(element);
last = first;
} else {
Node p = first;
Node elementTobeAdded;
while (((p.value).compareTo(element)) > 0 && p.next != null) {
p = p.next;
}
if (p.next != null) {
elementTobeAdded = new Node(element, p, p.next);
p.next.prev = elementTobeAdded;
p = elementTobeAdded.prev;
} else {
elementTobeAdded = new Node(element, p, null);
p.next = elementTobeAdded;
elementTobeAdded.next = null;
last = elementTobeAdded;
}
}
}
public void printForward() {
Node printNode = first;
while (printNode != null) {
System.out.print(printNode.value + ", ");
printNode = printNode.next;
}
}
}
public class test {
public static void main(String[] args) {
doubleLinkedList car = new doubleLinkedList();
car.add("Jeep");
car.add("benz");
car.add("Honda");
car.add("Lexus");
car.add("BMW");
car.printForward();
}
}
My add method is trying to add nodes to a list in alphabetical order. My printForward method prints out each element in the list.
In my main method, it prints out "Jeep, benz, Honda, BMW,", which is not in alphabetical order.
Change the not empty case for your add method from this
Node p = first;
Node elementTobeAdded;
while(((p.value).compareTo(element)) > 0 && p.next != null)
{
p = p.next;
}
if(p.next != null)
{
elementTobeAdded = new Node(element,p,p.next);
p.next.prev = elementTobeAdded;
p = elementTobeAdded.prev;
}
else
{
elementTobeAdded = new Node(element, p, null);
p.next = elementTobeAdded;
elementTobeAdded.next = null;
last = elementTobeAdded;
}
to this:
Node p = first;
while (p.value.compareTo(element) < 0 && p.next != null) {
p = p.next;
}
if (p.value.compareTo(element) > 0) {
Node toAdd = new Node(element, p.prev, p);
p.prev = toAdd;
if (toAdd.prev != null) {
toAdd.prev.next = toAdd;
}else {
first = toAdd;
}
}else {
Node toAdd = new Node(element, p, p.next);
p.next = toAdd;
if (toAdd.next != null) {
toAdd.next.prev = toAdd;
}else {
last = toAdd;
}
}
There were many errors here. The biggest one was that you never checked for the case where the new element should be inserted at the beginning of the list. A new element was always inserted after the first element even if it should have come first.
Note that "benz" comes at the end because the String.compareTo method treats capitals as coming before lower case letters.
It is not an a linked list... You wrote some sort of Queue (with optional possibility to make it Dequeue).
About your question - you have an error in your 'add' method - at least you don't check if it is necessary to move head forward. It is possible that you have another bugs, but it is too hard to read such styled sources (please fix your question formatting)...
I'm creating a method to add nodes into the list. The method will have the value and the position where the user wants the node. I'm able to add the node anywhere but the start of the list.
I have also added the toString method so there is an idea of how the it is to be displayed. At the bottom I added what main has.
//ADD A NODE
public boolean add(double val, int pos)
{
Node t = root;
Node n = new Node();
int count = 1;
if(pos-1 == 0)
{
n.next = t;
t = n;
n.val = val;
}
else
while(t != null)
{
if(pos-1 == count)
{
n.next = t.next;
t.next = n;
n.val = val;
}
t = t.next;
count++;
}
return true;
}
//toString Method
public String toString()
{
String s = "Contents of list: \n";
if( root == null )
s = s + "\tThe list is empty!";
Node t = root;
while(t != null)
{
s = s + t.val + "\t";
t = t.next;
}
return s;
}
//Main
//Add Node to list
list.add(105.0, 1);
System.out.println( list );
if(pos-1 == 0)
{
n.next = t;
root = n;
n.val = val;
}
Fix this so that root is modified.