I want to have a linked list containing an object
Here we have the class.
It is simple and only has a String and one int. Called s and n respectively.
public class test {
String string = new String ();
int n;
public metodo (String string, int n ){
sets(string);
setn(n);
}
public void sets(String string){
this.string = string;
}
public void setn(int n){
this.n = n;
}
public String gets(){
return string;
}
public int getn(){
return n;
}
}
In each node there will be an instance of the class test.
I want to be able to call each node and then call the object in the node calling the class test.
Here is my linked list
import java.io.*;
public class Node
{
BufferedReader br = new BufferedReader( new InputStreamReader ( System.in));
test m;
int n;
static Node next = null;
String string = new String ();
Nodo head = null;
public Nodo (test m, Nodo next) {
this.next = next;
}
public void hoho() throws IOException{
while ( true )
{ // This loop is for making several nodes with diferent information
System.out.println("String");
string n = br.readLine();
System.out.println(" Int ");
n = Integer.parseInt(br.readLine());
m = new test(string, n);
Nodo nod = new Nodo (m, null);
Nodo.siguiente = head;
head = nod;
if ( n == 0 ){ // Manual close of the loop by inserting 0
break;
}
}
}
}
Now I don't really know when to start the object m, if in the start or in the while.
Related
I am trying to sort a linked list with a bubble sort method, but when I try to sort the elements they remain unsorted. When I call my linked method it builds a linked list with parameters n and m which indicate length of the linked list and it represents a set of random integers m-1
Node class
public class iNode{
public int item;
public iNode next;
public iNode(int i, iNode n){
item = i;
next = n;
}
public iNode(int i){
item = i;
next = null;
}
// Node class
public int getItem() {
return this.item;
}
Node List class
public class iNode_List {
public static iNode head;
public static int size;
public iNode_List(){
this.head = null;
this.size = 0;
}
public static iNode linked(int n, int m){ // builds linked list
iNode previous;
iNode current;
int i = 0;
previous = null;
while (i < n) {
current = new iNode(ThreadLocalRandom.current().nextInt(0, m-1), previous);
previous = current;
head = current;
i++;
}
return previous;
}
public static void print() { // prints linked list
iNode currentNode = head;
while(currentNode != null) {
int data = currentNode.getItem();
System.out.println(data);
currentNode = currentNode.next;
}
}
public static void Bubble_Sort (){ // bubble sort method
if (size > 1) {
for (int i = 0; i < size; i++ ) {
iNode currentNode = head;
iNode next = head.next;
for (int j = 0; j < size - 1; j++) {
if (currentNode.item > next.item) {
int temp = currentNode.item;
currentNode.item = next.item;
next.item = temp;
}
currentNode = next;
next = next.next;
}
}
}
}
List class
public class list {
public static void main (String [] args) throws IOException{
iNode_List x = new iNode_List();
int choice;
x.linked(10, 9);
x.print();
System.out.println();
System.out.println("Which method would you like to implement? "); // method --------
Scanner scan = new Scanner (System.in);
choice = scan.nextInt();
switch (choice) {
case 1 : Compare_Loop(x) ;
break ;
case 2 : Bubble_Sort( x) ;
break ;
case 3 : Merge_Sort( x);
break ;
case 4 : Boolean( x);
break ;
}
}
public static void Compare_Loop (iNode_List x){
System.out.println();
x.Compare_Loop();
x.print();
}
public static void Bubble_Sort(iNode_List x){
System.out.println();
x.Bubble_Sort();
x.print();
}
public static void Merge_Sort(iNode_List x){
System.out.println();
x.Merge_Sort(null);
x.print();
}
public static void Boolean (iNode_List x){
System.out.println();
//x.Boolean();
x.print();
}
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();
}
}
public class AdjList {
private Node first; // beginning of list
private int N; // size of lis
private static class Node {
int a;
Node next;
Node(int a, Node next) {
this.a = a;
this.next = next;
}
}
public boolean isEmpty() { return (first == null); }
public int size() { return N; }
public void insert(int a) {
first = new Node(a, first);
N++;
}
public static void main(String[] args) {
AdjList adjlist = new AdjList();
adjlist.insert(1);
adjlist.insert(2);
adjlist.insert(3);
adjlist.insert(4);
System.out.println(adjlist);
}
}
i am trying to write a code on adjacency list using linked list.data items are integers,but it shows error
this is the code i have tried .but it return some other values.can u help me
AdjList#6e1408 is the output
You need two toString() methods, perhaps something like this for the AdjList
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("AdjList [").append(N).append("] = {");
Node n = this.first;
for (int i = 0; i < N; i++) {
if (i != 0) {
sb.append(", ");
}
sb.append(n.toString());
n = n.next;
}
sb.append("}");
return sb.toString();
}
Then for your Node you need another one, perhaps something like this
public String toString() {
return String.valueOf(a);
}
I think you will get something more like what you expected if you try those.
I have to write a program in which I have to create a singly linked list dictionary in alphabetical order. Then have the words in the dictionary searched in a text file then do a intersect method to see if any word(s) intersect. So far I have created the text file as well as created the two nodes and done the mapping to search for how many times each word appears in this text file. I am completely lost on how to create the singly linked dictionary. I was planning on creating two linked lists(Each with about 5 words in them) and then running an intersection alogirthm method. WOuld that be correct? Or is there an easier way to do it with the code I already have. Here is my code so far:
public class dictionary
{
//variables
dNode head;
int size;
//constructor
public dictionary()
{
head = null;
size = 0;
}
//addFirst method
public void addFirst(dNode s)
{
s.setNext(head);
head = s;
size++;
}
public void addLast(dNode s)
{
if ( head == null )
{
head = s;
}
else
{
s.setNext(null);
dNode w = head;
while ( w.getNext() != null )
{
w = w.getNext();
}
w.setNext(s);
}
size++;
}
//toString Method
public String toString()
{
String w = "";
dNode s = head;
while ( s != null )
{
w += s + "\n";
s = s.getNext();
}
return w;
}
}
public class dNode
{
//variables
String sent;
posting post;
dNode nextNode;
//constructor
public dNode(String sent, posting post, dNode nextNode)
{
this.sent = sent;
this.post = post;
this.nextNode = nextNode;
}
//returns element of this node
public String getSent() {
return sent;
}
//retunrs the next node of this node
public dNode getNext() {
return nextNode;
}
//modifier methods
//sets elements of this node.
public void setSent(String newSent) {
sent = newSent;
}
//sets the next node of this node
public void setNext( dNode newNext) {
nextNode = newNext;
}
//toString method
public String toString()
{
return "Sentence and Posting: \n" + sent + "\n" + post;
}
}
public class pNode {
//variables
int dID;
String word;
int occurence;
pNode next;
//constructor
public pNode(int dID, String word, int occurence, pNode next)
{
this.dID = dID;
this.word = word;
this.occurence = occurence;
this.next = next;
}
//return element of this node
public String getWord() {
return word;
}
//Returns the next node of this node
public pNode getNext() {
return next;
}
//Modifier methods
//set the words of this node
public void setWord(String newWord) {
word = newWord;
}
//sets the next node of this node
public void setNext(pNode newNext){
next = newNext;
}
//toString method
public String toString() {
return "Document ID, Word, Occurence: \n " + dID + ", "
+ word + ", " + occurence;
}
}
public class posting
{
//variables
pNode head;
int size;
//constructor
public posting()
{
head = null;
size = 0;
}
//addFirst method
public void addFirst(pNode s)
{
s.setNext(head);
head = s;
size++;
}
//addLast method
public void addLast(pNode s)
{
if ( head == null )
{
head = s;
}
else
{
s.setNext(null);
pNode w = head;
while ( w.getNext() != null )
{
w = w.getNext();
}
w.setNext(s);
}
size++;
}
//toString method
public String toString()
{
String w = "";
pNode s = head;
while ( s != null)
{
w += s + "\n";
s = s.getNext();
}
return w;
}
}
import java.io.*;
import java.util.*;
public class testFile
{
public static void main (String[] args) throws FileNotFoundException
{
File filename = new File("/export/home/hawkdom2/s0878044/CS503/assignment2/sentences.txt");
Scanner scan = new Scanner(filename);
dictionary Dictionary = new dictionary();
while ( scan.hasNextLine() )
{
String sentence = scan.nextLine();
String[] word = sentence.split(" ");
//first element is document id
int dID = Integer.parseInt( word[0] );
//insertion sort
for ( int i = 2; i < word.length; i++ )
{
for ( int j = i; j > 1; j-- )
{
if ( word[j].compareTo( word[j-1] ) > 0 )
{
String switchs = word[j];
word[j] = word[j-1];
word[j-1] = switchs;
}
}
}
//integer array count
int[] count = new int[word.length];
for ( int i = 1; i < word.length; i++)
{
for ( int j = 1; j < word.length; j++)
{
if (word[i].equalsIgnoreCase( word[j] ) )
{
count[i]++;
}
}
}
posting posts = new posting();
for ( int i = 1; i < word.length; i++ )
{
if ( (i > 1 ) && (word[i].equalsIgnoreCase( word[i-1] ) ) )
continue;
else
{
posts.addFirst(new pNode(dID, word[i], count[i], null) );
}
}
Dictionary.addLast(new dNode(sentence, posts, null) );
}
String[]words ={"cat", "chased", "dogs", "mammals", "roses"};
LinkedList<String> list1 = new LinkedList<String>();
for (String x : words)
list1.add(x);
String[] words2 = {"dislikes", "favorite", "likes", "pink", "red"};
LinkedList<String> list2 = new LinkedList<String>();
for (String y : words2)
list2.add(y);
//print out output
System.out.println(Dictionary);
}
}
And this is my text file containing the sentences:
1 a rose is a rose
2 John chased a cat and the cat chased John
3 cats are mammals but mammals are not cats
4 beavers build dams but i know a beaver that does not
5 my dog chased a cat and the cat attacked my dog
6 my dog likes cats but my cat dislikes dogs
7 my dog likes roses but roses dislike my dog
8 my cat dislikes roses but roses like my cat
9 red roses are not my favorite roses
10 my favorite roses are pink roses
I got the following assignment - I have a certain java code for a binary search tree and I need to add methods to do the following things with it:
Transform the BST into an array that's sorted by BST data keys.
Create a balanced BST from an ordered integer array.
Use 1. and 2. to balance an existing BST (randomly generated and presumably somewhat unbalanced)
Display the BST before and after balancing.
Please guys, help me if you're smarter than me and know how can that be achieved!
Here is the code that I need to work with:
import java.util.*;
class BtreeNode {
int data;
BtreeNode L,R;
static int depth=0;
public BtreeNode(){
data = 0; L = null; R=null;
}
public BtreeNode(int key){
this();data = key;
}
public String toString() {
return "["+data+"]";
}
public static BtreeNode insOrd(BtreeNode roo, int key){
if(roo==null)return new BtreeNode(key);
//Не се допуска повторение на ключове
if(key==roo.data)return roo;
if(key<roo.data)roo.L=insOrd(roo.L,key);
else roo.R=insOrd(roo.R,key);
return roo;
}
public static BtreeNode generate(int length) {
BtreeNode start = null;
Random rn = new Random();
for(int i = 0; i < length; i++){
start = insOrd(start,rn.nextInt(10000));
}
return start;
}
public static void spc(int n){
for(int i=0;i<n;i++)System.out.print(" ");
}
public static void print(BtreeNode roo){
if(roo!=null){
depth++;
print(roo.R);
spc(depth);System.out.println(roo);
print(roo.L);
depth--;
}
}
public static BtreeNode find(BtreeNode roo, int key){
BtreeNode r=null;
if(roo==null)return r;
if(roo.data==key)r= roo;
if(key>roo.data)r= find(roo.R,key);
if(key<roo.data)r= find(roo.L,key);
return r;
}
};
public class Main {
public static void main(String[] args){
int N;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number if tree items:");
N=sc.nextInt();
BtreeNode c = BtreeNode.generate(N);
BtreeNode.print(c);
/*
System.out.println("This tree has "+
BtreeNode.weight(c)+" nodes and "+
BtreeNode.height(c)+" levels.");
*/
}
}
UPDATE:
Thank you soooo much guys for your great help, you can't imagine how grateful I am for your advice!!!
I have the whole program working. I am going to post it because somebody might need something like that sometime.
import java.util.*;
class BtreeNode {
int data;
BtreeNode L,R;
static int depth=0;
public BtreeNode(){
data = 0; L = null; R=null;
}
public BtreeNode(int key){
this();data = key;
}
public String toString() {
return "["+data+"]";
}
public static ArrayList<BtreeNode> asList(BtreeNode node) {
ArrayList<BtreeNode> result = new ArrayList<BtreeNode>();
traverse(node, result);
Collections.sort(result, new Comparator<BtreeNode>() {
#Override
public int compare(BtreeNode arg0, BtreeNode arg1) {
if (arg0.data < arg1.data)
return -1;
else if (arg0.data > arg1.data)
return 1;
return 0;
}
});
return result;
}
private static void traverse(BtreeNode node, ArrayList<BtreeNode> result) {
if (node.L != null) {
traverse(node.L, result);
}
result.add(node);
if (node.R != null) {
traverse(node.R, result);
}
}
public static BtreeNode sortedArrayToBST (ArrayList<BtreeNode> result, int start, int end) {
if (start > end) return null;
// same as (start+end)/2, avoids overflow.
int mid = start + (end - start) / 2;
BtreeNode node = new BtreeNode(result.get(mid).data);
node.L = sortedArrayToBST(result, start, mid-1);
node.R = sortedArrayToBST(result, mid+1, end);
return node;
}
public static BtreeNode insOrd(BtreeNode roo, int key){
if(roo==null)return new BtreeNode(key);
if(key==roo.data)return roo;
if(key<roo.data)roo.L=insOrd(roo.L,key);
else roo.R=insOrd(roo.R,key);
return roo;
}
public static BtreeNode generate(int length) {
BtreeNode start = null;
Random rn = new Random();
for(int i = 0; i < length; i++){
start = insOrd(start,rn.nextInt(10000));
}
return start;
}
public static void spc(int n){
for(int i=0;i<n;i++)System.out.print(" ");
}
public static void print(BtreeNode roo){
if(roo!=null){
depth++;
print(roo.R);
System.out.print("Level "+depth);
spc(depth);
System.out.println(roo);
print(roo.L);
depth--;
}
}
public static BtreeNode find(BtreeNode roo, int key){
BtreeNode r=null;
if(roo==null)return r;
if(roo.data==key)r= roo;
if(key>roo.data)r= find(roo.R,key);
if(key<roo.data)r= find(roo.L,key);
return r;
}
};
public class Main {
public static void main(String[] args){
int N;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number if tree items:");
N=sc.nextInt();
BtreeNode c = BtreeNode.generate(N);
BtreeNode.print(c);
System.out.println("********************");
/*
System.out.println("This tree has "+
BtreeNode.weight(c)+" nodes and "+
BtreeNode.height(c)+" levels.");
*/
ArrayList<BtreeNode> result = BtreeNode.asList(c);
for (BtreeNode btreeNode : result) {
System.out.println(btreeNode.data);
}
// insert in sorted order
c = result.get(0);
for (int i = 1; i < result.size(); i++) {
BtreeNode.insOrd(c, result.get(i).data);
}
BtreeNode.print(c);
System.out.println("********************");
BtreeNode d = BtreeNode.generate(N);
BtreeNode.print(d);
System.out.println("********************");
ArrayList<BtreeNode> result2 = BtreeNode.asList(d);
for (BtreeNode btreeNode : result2) {
System.out.println(btreeNode.data);
}
System.out.println("********************");
BtreeNode.print(BtreeNode.sortedArrayToBST(result2, 0, result2.size()-1));
}
}
Well for the first point you have to have a global array and a traverse method.
Traverse method shoould work something like this:
in main method at the end add this:
ArrayList<BtreeNode> result = BtreeNode.asList(c);
for (BtreeNode btreeNode : result) {
System.out.println(btreeNode.data);
}
// insert in sorted order
c = result.get(0);
for (int i = 1; i < result.size(); i++) {
c.insOrd(c, result.get(i).data);
}
BtreeNode.print(c);
add this methods to BtreeNode class:
public static ArrayList<BtreeNode> asList(BtreeNode node) {
ArrayList<BtreeNode> result = new ArrayList<BtreeNode>();
traverse(node, result);
Collections.sort(result, new Comparator<BtreeNode>() {
#Override
public int compare(BtreeNode arg0, BtreeNode arg1) {
if (arg0.data < arg1.data)
return -1;
else if (arg0.data > arg1.data)
return 1;
return 0;
}
});
return result;
}
private static void traverse(BtreeNode node, ArrayList<BtreeNode> result) {
if (node.L != null) {
traverse(node.L, result);
}
result.add(node);
if (node.R != null) {
traverse(node.R, result);
}
}
1) Creating the sorted array can be done with an "inorder tree walk" - it's fairly easily implementable as a recursive function that you start on the root node. It would look something like this:
void addToListInOrder(List<BtreeNode> l) {
if(L != null) {
L.addToListInOrder(l);
}
list.add(this);
if(R != null) {
R.addToListInOrder(l);
}
}
2) A recursive algorithm would work well here as well: Pick a point in the middle (round up or down if needed) and pick that as the root node. Then subdivide the remaining points in two lists, those before and those after the chosen node, and then call the algorithm recursively on those. Then set the results as the left and right child of the current node. and finally return the node that was chosen. Be sure to handle lists with only a single or a few nodes correctly
3) Do 1 and then 2 on the BST to get a balanced recreation.
4) I've used graphviz for some nice visualizations in the past, but that's probably beyond the scope of your assignment. In it I used an inorder graph walk to create the source file for graphviz
Just check http://www.roseindia.net/java/java-get-example/java-binary-tree-code.shtml
For all of these operation you should use reqursion with end check for current node if it hasn't got more childs.