Insert Method infinite loop in a doublylinkedlist - loops

I may just be entirely ignorant to what is happening here but i've looked over it a million times and i'm sure it is something obvious but my insert method infinitely loops due to the while loop. Any help would be appreciated.
Here is the code..
package dcjaniszewskiOL4;
public class DoublyLinkedList<T extends Comparable> {
private class Node<T>
{
private T data;
private Node<T> next;
private Node<T> prev;
private Node(T d){
data=d;
next=null;
prev=null;
}
private Node( T d, Node<T> pref, Node<T> nref){
data=d;
prev=pref;
next=nref;
}
}
private Node<T> head;
private Node<T> current;
private int size;
public DoublyLinkedList(){
head = new Node<T>(null,null,null);
current=head.next;
size=0;
}
public DoublyLinkedList(DoublyLinkedList<T> i){
}
public void insert (T d){
Node<T> ptr, trav, prev;
prev=null;
begin();
trav=head.next;
if(empty()){
head.next = new Node<T>(d,head,head);
}
while(trav!=null){
System.out.println(trav.data);
prev=trav;
advance();
trav=current;
}
ptr = new Node<T> (d, prev,head);
if(prev==null){
head.next=ptr;
head.prev=ptr;
}
else{
prev.next=ptr;
current.prev=ptr;
}
size++;
}
public void remove(T d) throws ListEmptyException, NotInListException{
Node<T> tmp = head;
if(head.next==null){
throw new ListEmptyException("List is empty on Remove");
}
while(tmp!=null){
if(tmp.data.equals(d)){
tmp.prev.next=tmp.next;
tmp.next.prev=tmp.prev;
size--;
}else{
tmp=tmp.next;
if(tmp==null){
throw new NotInListException("Item is not in the list");
}
}
}
}
public void begin(){
current=head.next;
}
public void advance(){
current.prev = current;
current=current.next;
}
public void retreat(){
current.next=current;
current=current.prev;
}
public T current() throws ListEmptyException{
if(current==null){
throw new ListEmptyException("List is empty");
}else{
return current.data;
}
}
public boolean end(){
boolean end = false;
if(current==null){
end=true;
}else{
end=false;
}
return end;
}
public boolean empty(){
boolean empty = false;
if(size()==0){
empty=true;
}else{
empty=false;
}
return empty;
}
public int size(){
return size;
}
}

try this
ptr = new Node<T> (d, null,null);
trav=head;
while (trav.next!= null)
{
trav = trav.next;
}
trav.next = ptr;
ptr.prev = trav;
Let me know if it doesn't work

Related

Why when I print my array of objects it shows all null?

I want to create a deck of cards(object), and it shows nullnullnull... however i construct the card.
This is the class I use to initialize the deck:
import black.jack.bean.Card;
public class InitDeck {
public InitDeck() {
}
public void createDeck(Card[] cards) {
for(int idx = 0; idx<cards.length; idx++) {
int contValueNum = 1;
boolean valueYes = false;
cards[idx] = new Card((char) idx, idx);
if(!valueYes) {
switch(contValueNum) {
case 1:
cards[idx].setKey('A');
cards[idx].setKeyValue(contValueNum);
break;
case 11:
cards[idx].setKey('J');
cards[idx].setKeyValue(contValueNum);
break;
case 12:
cards[idx].setKey('Q');
cards[idx].setKeyValue(contValueNum);
break;
case 13:
cards[idx].setKey('K');
cards[idx].setKeyValue(contValueNum);
break;
}
if(idx==cards.length) {
valueYes = false;
}
}
}
}
public void visDeck(Card[] cards) {
for(int idx = 0; idx<cards.length; idx++) {
System.out.print(cards[idx]);
}
}
}
This is the class Deck and the class Card
public class Deck {
private static final int CARDS = 52;
//private char[] deck = new char[CARDS];
protected Card[] cards = new Card[CARDS];
public Deck() {
}
public Card[] getCards() {
return cards;
}
public void setCards(Card[] cards) {
this.cards = cards;
}
}
public class Card {
public char key;
public int keyValue;
public Card(char key, int keyValue) {
this.key = key;
this.keyValue = keyValue;
}
public Card() {
}
public char getKey() {
return key;
}
public void setKey(char key) {
this.key = key;
}
public int getKeyValue() {
return keyValue;
}
public void setKeyValue(int keyValue) {
this.keyValue = keyValue;
}
}
And this is my Console
public class Console {
public Console() {
}
public void execute() {
InitDeck initDeck= new InitDeck();
Deck deck = new Deck();
Card card = new Card();
initDeck.visDeck(deck.getCards());
}
}
And the result is:
nullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnullnull
There's someone who could help me out?

downloadUrlToStorageInBackground in ImageList model for imageViewer downloads & overrides the image every time

class ImageList implements ListModel<Image> {
private int selection;
private Image[] images;
private EventDispatcher listeners = new EventDispatcher();
public ImageList() {
this.images = new EncodedImage[imageURLs.length];
}
public Image getItemAt(final int index) {
if (images[index] == null) {
images[index] = placeholderForTable;
Util.downloadUrlToStorageInBackground(imageURLs[index], "list" + index, (e) -> {
try {
images[index] = EncodedImage.create(Storage.getInstance().createInputStream("list" + index));
listeners.fireDataChangeEvent(index, DataChangedListener.CHANGED);
} catch (IOException err) {
err.printStackTrace();
}
});
}
return images[index];
}
public int getSize() {
return imageURLs.length;
}
public int getSelectedIndex() {
return selection;
}
public void setSelectedIndex(int index) {
selection = index;
}
public void addDataChangedListener(DataChangedListener l) {
listeners.addListener(l);
}
public void removeDataChangedListener(DataChangedListener l) {
listeners.removeListener(l);
}
public void addSelectionListener(SelectionListener l) {
}
public void removeSelectionListener(SelectionListener l) {
}
public void addItem(Image item) {
}
public void removeItem(int index) {
}
}
protected void postMenuForm(Form f) {
BusinessForumImagesConnection bfic = new BusinessForumImagesConnection();
bfic.businessForumImagesConnectionMethod(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
if (bfic.response != null) {
for (int i = 0; i < imgLoop; i++) {
HashMap hm = (HashMap) bfic.response.get(i);
String imgUrl = (String) hm.get("imgUrl");
imageURLs[i] = imgUrl;
}
}
}
});
if (imageURLs != null) {
ImageList imodel = new ImageList();
ImageViewer iv = new ImageViewer(imodel.getItemAt(0));
iv.setImageList(imodel);
Container adsContainer = BoxLayout.encloseY(adsLabel, iv);
slideIndex = 0;
Runnable r = new Runnable() {
public void run() {
if (slideIndex < imodel.getSize()) {
nextImage = (Image) imodel.getItemAt(slideIndex);
if (nextImage != null) {
iv.setImage(nextImage);
}
slideIndex++;
} else {
slideIndex = 0;
}
}
};
if (uITimer == null) {
uITimer = new UITimer(r);
}
if (uITimer != null) {
uITimer.schedule(5000, true, f); //5 seconds
}
f.add(BorderLayout.SOUTH, adsContainer);
adsContainer.setLeadComponent(adsLabel);
adsLabel.addActionListener((e) -> {
showForm("BusinessForum", null);
});
}
}
I had used URLImage.createToStorage before but imageViewer didnt work properly so I have used ImageList model. But everytime the form is opened, it jst redownloads the imgs and overrides them in storage, that makes the app slower. How can I make sure if the image is already downloaded, it doesnt download it again and jst shows them in imgViewer? thankyou
The download method will always download regardless...
You need to check if the Storage file exists and if so load that.
See the WebServices/Dogs demo in the new kitchen sink: http://www.codenameone.com/blog/kitchensink-ii.html

Java Link strategy for array implementation of trees?

My Question:
I have a Java program that searches for the Lowest Common Ancestor in a Binary Tree. That part should work, but my question is regarding my main method so I haven't properly tested it. I need to create a binary tree from the chars stored in my array.
What I've found
To put it simply, not much. I've found a few pages that touch on the subject, but their implementations seem so vastly different from the rest of my code. If someone can even provide links to a guide, preferably with code examples, that could possibly answer my question.
My Code
public class TreeMain
{
static TreeNode root;
public static void main(String args[])
{
String[] myStringsChars = new String[26];
for(int i = 0; i < 26; i++)
{
myStringChars[i] = new String(Character.toChars(i+65));
System.out.println(myStringChars[i]);
}
// array to binary tree
TreeNode commonAncestor = findLowestCommonAncestor(firstNode, secondNode);
if(commonAncestor != null) {
System.out.println(commonAncestor.getContents()); }
}
public static TreeNode findLowestCommonAncestor(TreeNode node1, TreeNode node2)
{
return findLCA(root, node1, node2);
}
public static TreeNode findLCA(TreeNode node, TreeNode node1, TreeNode node2)
{
if (node == null) {
return null; }
if (node.getContents() == node1 || node.getContents() == node2) {
return node; }
TreeNode leftLCA = findLCA(node.getLeftChild(), node1, node2);
TreeNode rightLCA = findLCA(node.getRightChild(), node1, node2);
if (leftLCA!=null && rightLCA!=null)
return node;
// Otherwise check if left subtree or right subtree is LCA
return (leftLCA != null) ? leftLCA : rightLCA;
}
}
public class TreeNode<T extends Comparable>{
private T contents;
private TreeNode<T> parent;
private TreeNode<T> leftChild;
private TreeNode<T> rightChild;
private int level;
public TreeNode(T data, TreeNode parent)
{
contents = data;
this.parent = parent;
}
public void setLeftChild(TreeNode node)
{
this.leftChild = node;
}
public void setRightChild(TreeNode node)
{
this.rightChild = node;
}
public boolean isContentEquals(T data)
{
return 0 == getContents().compareTo(data);
}
public T getContents() {
return contents;
}
public void setContents(T contents) {
this.contents = contents;
}
public TreeNode getParent() {
return parent;
}
public void setParent(TreeNode parent) {
this.parent = parent;
}
public TreeNode getLeftChild() {
return leftChild;
}
public TreeNode getRightChild() {
return rightChild;
}
public TreeNode findNodeOnTree(T contentToSearch)
{
List<TreeNode> nodes = new LinkedList();
nodes.clear();
nodes.add(this);
while(!nodes.isEmpty())
{
TreeNode current = nodes.remove(0);
if(current.isContentEquals(contentToSearch))
{
return current;
}
if(current.leftChild != null)
{
nodes.add(current.leftChild);
}
if(current.rightChild != null)
{
nodes.add(current.rightChild);
}
}
return null;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
}
I haven't tried your algorithm yet, but the part you are looking for should be pretty straightforward. One quick way to achieve it would be to draw the picture of the binary tree you have in mind and just write a couple of methods to translate that picture to code. Here's what I'd start with:
public TreeNode<T> addLeft(T key) {
TreeNode<T> tmp = new Node<>(key);
this.left = tmp;
tmp.parent = this; // if you are using parent pointers
return tmp; // for chaining purpose, so returned node can be subject to addition
}
public TreeNode<T> addRight(T key) {
TreeNode<T> tmp = new TreeNode<>(key);
this.right = tmp;
tmp.parent = this;
return tmp;
}
To construct the tree, you can create a root node and then call the addLeft() and addRight() methods as you see in the picture of your binary tree:
TreeNode<Character> root = ...; // say root's key is 'A'
TreeNode<Character> left1 = root.addLeft('B');
TreeNode<Character> right1 = root.addRight('C');
//TreeNode<Character> left2 = left1.addLeft();
// and so on for your character array.
A more involved way is to think of the inorder traversal and preorder traversal of the tree that you have in mind, represent the two traversals as two separate arrays and then write another procedure to accept these two arrays that constructs a binary tree out of this. This is left as an exercise.

Populate Winforms treeview with Sharepoint site

I'm very new to sharepoint and I have to a task with it.
I have my site adress but just about it.
I need to populate a treeview with all the hierarchy from SPSite and down for my sharepoint site using C#;
I guess I need to use recursive functions to do so...
can anyone help?
thank you.
Solved!
public void FillTreeSPWeb(SPWeb MySPWeb, TreeNode Node, int num)
{
if (num <= 0)
{
Node.Text = MySPWeb.Title;
GetSPDocumentLibrary(MySPWeb, Node);
}
num--;
foreach (SPWeb item in MySPWeb.Webs)
{
TreeNode Child = new TreeNode();
FillTreeSPWeb(item, Child,num);
Node.Nodes.Add(Child);
}
}
public void GetSPDocumentLibrary(SPWeb MySPWeb,TreeNode Node)
{
foreach (SPList item1 in MySPWeb.Lists)
{
if (item1.BaseType == SPBaseType.DocumentLibrary)
{
SPDocumentLibrary oDocumentLibrary = (SPDocumentLibrary)item1;
try
{
TreeNode Child = new TreeNode(oDocumentLibrary.Title);
GetFiles(oDocumentLibrary.RootFolder, Child);
foreach (SPListItem item in oDocumentLibrary.Folders)
{
TreeNode GrandChild = new TreeNode();
FillFilesAndFolders(item.Folder, GrandChild);
Child.Nodes.Add(GrandChild);
}
Node.Nodes.Add(Child);
}
catch { }
}
}
}
public void FillFilesAndFolders(SPFolder MySPFolder, TreeNode Node)
{
Node.Text = MySPFolder.Name;
GetFiles(MySPFolder, Node);
foreach (SPFolder item1 in MySPFolder.SubFolders)
{
FillFilesAndFolders(item1, Node);
}
}
public void GetFiles(SPFolder MySPFolder,TreeNode Node)
{
foreach (SPFile item in MySPFolder.Files)
{
Node.Nodes.Add(item.Name);
}
}

Balancing in AVL tree only in main root

I am creating AVL binary tree in which the only problem is that the root is not changes its position or gets balance except all other child's root or leaves etc
Any help would be greatly appreciated!
Logical Layer file
public class Node
{
public int data;
public Node left, right;
public Node(int data)
{
this.data = data;
left = null;
right = null;
}
}
public class BinaryTree
{
public Node root;
public BinaryTree()
{
root = null;
}
public int height(Node temp)
{
int h = 0;
if (temp != null)
{
int l_height = height(temp.left);
int r_height = height(temp.right);
int max_height = Math.Max(l_height, r_height);
h = max_height + 1;
}
return h;
}
public int diff(Node temp)
{
int l_height = height(temp.left);
int r_height = height(temp.right);
int b_factor = l_height - r_height;
return b_factor;
}
Node rr_rotation(Node parent)
{
Node temp;
temp = parent.right;
parent.right = temp.left;
temp.left = parent;
return temp;
}
Node ll_rotation(Node parent)
{
Node temp;
temp = parent.left;
parent.left = temp.right;
temp.right = parent;
return temp;
}
Node lr_rotation(Node parent)
{
Node temp;
temp = parent.left;
parent.left = rr_rotation(temp);
return ll_rotation(parent);
}
Node rl_rotation(Node parent)
{
Node temp;
temp = parent.right;
parent.right = ll_rotation(temp);
return rr_rotation(parent);
}
Node balance(Node temp)
{
int bal_factor = diff(temp);
if (bal_factor > 1)
{
if (diff(temp.left) > 0)
temp = ll_rotation(temp);
else
temp = lr_rotation(temp);
}
else if (bal_factor < -1)
{
if (diff(temp.right) > 0)
temp = rl_rotation(temp);
else
temp = rr_rotation(temp);
}
return temp;
}
public Node addNode(int data) // It only add the Root(that is 55 in the fig)
{
Node newNode = new Node(data);
if (root == null)
{
root = newNode;
}
return root;
}
public Node insertNode(Node root, int newNode) //But I want to make this should add root node.
{
if (root == null) (I think here is some problem)
{
root = new Node(newNode);
root.data = newNode;
root.left = null;
root.right = null;
return root;
}
if (newNode < root.data)
{
root.left = insertNode(root.left, newNode);
root = balance(root);
}
else if (newNode >= root.data)
{
root.right = insertNode(root.right, newNode);
root = balance(root);
}
return root;
}
}
Presentataion layer file
public partial class PresentationLayer : Form
{
BinaryTree obj = new BinaryTree();
int a, b;
public PresentationLayer()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e) //add node button
{
int num = 0;
bool result = int.TryParse(textBox1.Text, out num);
if (result)
{
a = Int32.Parse(textBox1.Text);
obj.addNode(a); //It creates root
textBox1.Hide();
button1.Hide();
}
}
private void button2_Click_1(object sender, EventArgs e) //insert button
{
int num = 0;
bool result = int.TryParse(textBox2.Text, out num);
if (result)
{
b = Int32.Parse(textBox2.Text);
Node abc = new Node(b);
obj.insertNode(obj.root, b); //It is not creating root
textBox2.Clear();
}
}
}
}
Any help would be greatly appreciated!
You should add cases into the ll_rotation and rr_rotation functions to handle when the root is rotated. You should be able to check if the parameter parent is the same node as root, and if so, set root to refer to the new rotated node.
For example, per Wikipedia's example of left rotation:
P
/ \
/ \
A Q
/ \
B C
Rotates Left to become:
Q
/ \
/ \
P C
/ \
A B
If ll_rotation(P) is called where P is the same node as root, then the function should assign Q to be the new root

Resources