I'm studying Cracking the Coding Interview, and the code for constructing a Node class has a int data variable. What is the point of this variable? What does it refer to in the list?
The field
int data
is an example of what you hold inside a node, an element that you actually care for in the list.
Let's say you want to keep a list of integers in given order. The data field is your integer (for example profit of your company in some preconfigured order), while the Node object encapsulates it and also holds a reference to the next object (in single linked list)
Related
This may be a too-specific question, but I'm hoping there's a more general solution to my problem.
I have a class. In this class is a tree-type structure with many parent/child nodes. Also in this class is an Array filled with references to each node in this tree-type structure.
The tree's purpose is for each node to know where to draw itself on screen (every node has relative positional information based on its parent's location).
The Array's purpose is the draw order, I simply draw whatever node is referenced at Array[0] first and so on. (So, the nodes aren't being drawn in the order they appear in the tree necessarily).
My problem is this. I want to clone this overall class that contains these two objects (tree with nodes and an Array that references said nodes). This seems simple.
I create a deep copy of the tree structure and the nodes it contains. Cool.
However, I don't know how to repopulate a new Array with references to these new nodes in this new tree. It seems like it would be simple but I can't figure out how to do it.
I tried to be specific enough to give enough information without being too confusing, hope you understand.
Thanks.
If you're able to change the node data structure, you could add a field for the node's array index. That way, once you've rebuilt your tree you can just walk through it and use the index field to repopulate the array. Not super elegant, but it gets the job done...
Or, to avoid adding a field to your node class, I suppose you could use a temporary hashtable that maps nodes to array indices. Walk through your source array to populate the hashtable, then once you've cloned the tree, walk through the tree, looking up the new nodes in the hashtable (which will work fine assuming you've implemented equals and hashCode properly) and populating the array from those.
In a Java application I need an structure to store, lets call them nodes, and the number of relationship with other nodes. For example, I would need to know that node A is related with B 3 times.
Thinking in a way to implement this I got to this possible solution: Have a hashmap using nodes as key and another hashmap as value. This hashmap would store nodes as key (node B in the example) and an integer as value representing the number of relationships.
What do you think about this? Is it a good approach?
If so, I have a question. Suppose tha I store strings and they come from a text file after apply String.split function. Now I store "hello" in the first hashmap but after processing the file, this string appears as a destiny node in the second hashmap. Would these strings have a reference to the same object or I'll have multiple copies of the same objects?
Regarding the first question, I would do something similar but different. Instead of creating a Hashmap inside a Hashmap I would create a new class Relationship that looks something like this:
public class NodeRelationship {
private Node relatedNode;
private int numOfRelations
// Constructor + getters and setters
}
And define your map like this: Map<Node, List<NodeRelationship>> This seems more readable to me (but maybe it's just me) and easier to later expend. For example if you iterate on the list and want to know the original node you can add a member parent to NodeRelationshio and so on.
Regarding the second question - it depends on how you create your objects and whether you create new objects or use existing ones. If you have a node hello that you put in your value Hashmap (or in the List in my solution) and you use the same object for creating a new key - so there's no duplication. If you don't have a way (or just don't search for) to know that the node was already created, and you create new node - then you'll have duplications of objects.
If indeed your each of your nodes is created from text string, you can maintain a new Map<String, Node> and in the process of reading the file you can maintain this map and check if an object exists before creating a new one. This is very low cost in performance and you can get rid of the map once the construction of the objects from text is done.
I've been asked to create and manage a link list from scratch without the use of the java util.
If I were to create an object which has more then one attribute e.g. name & age then would it be possible to store the object within the link list?
I'm having a hard time trying to get my head around this and would appreciate any help!
Here's my pseudo code:
Classes:
Node
LList
Person
Address
add_person
sout "Enter name"
scan.next(String name)
pass name to setName (a Person class function)
sout "Enter postcode"
scan.next(String postCode)
pass postCode to setPostCode (a Address class function)
How would I then go about linking these two bits of information together within the same link list?
Edit: Thanks for the input guys, I'll have a good read about based upon your recommendations! Once again many thanks! :)
Try looking up what a linked list is and how it needs to be constructed. Your psuedo code has nothing to do with a linked list, only some rudimentary data entry. I suggest you look over the following link to understand what it is and how it works. The actual coding is fairly simple once you understand the structure.
I encourage others to not do your homework for you.
Wikipedia
Its not too tough, you just need to create your own Node class. This class might look something like this:
public class Node{
protected String name;
protected int age;
//any additional data you need...
protected Node next;
//methods...
This class would contain many data fields and would provide methods to interact with these fields. The key component is the "protected Node next;" line, which is the next node in the linked list. All nodes in the list would have a next node, except for the tail. The tail node would set next equal to null.
First you need to define a basic building bloc of a linked list which is Node. Nodes are like containers that store whatever you want. That's why storedData variable is of type Object. You would define it like this:
public class MyNode{
Object storedData; // this is a reference to the object that you want stored in the list
MyNode next; //this is a reference to the next node in your list
...
}
Then you can define your linked list class, which would go like this:
public class MyLinkedList{
MyNode head; //this is a reference to the top element of your list
int nodeCount //
//put all the requkired methods here
}
You should write your own LinkedList that uses generics; let it handle any object type.
You name and post code and age and whatnot ought to be encapsulated in an object that you'd be able to add to the LinkedList.
package linkedlist;
public class Node<T> {
private Node<T> prev;
private Node<T> next;
private T value;
}
Cat------>Dog------>Horse----->Parrot
^P1 ^P2 ^P3 ^P4
Draw the resulting linked list after executing the following statements:
P4 = P2;
P3.info = P2.info
etc.
My question is, what does '.info' reference?
I've looked in the API for both node and linked list and haven't found anything.
Any ideas?
This would entirely depend on the specific implementation used in your assignment, but it sounds like info contains the data of the specific node in the linked list, i.e. P1.info is Cat.
Each node in a standard linked list has two pieces of information:
A reference the the next node
The data contained in the current node
I'm not sure if your instructor wants you to take into account that you would have to "clone" the node in order to have a separate object with the same data or if your instructor wants you to take it literally where setting one object equal to another object simply makes the first one a reference to the second one.
As spookyjon said, the info appears to be a public variable in the node class for the data (cat, dog, horse, parrot).
I'm trying to create binary tree that contains two int values and one string value sorted in the lexicographic, but I'm not sure what to do. I've created an array list, which has been already sorted, but the binary tree has to be a reference-based which is not sorted and I'm thinking about sorting the list while creating it. Can any one help with this? Any brief idea would be appreciated.
Binary tree is a recursive thing. Make a class called BinaryTree (i hope you are in C++, or .NET or JAVA) that has two references to two other BinaryTrees (null by default). Then make an insert function that is recursive.
I don't know what you are trying to accomplish, but when building a binary tree, arrays are usually nowhere to be found.
You first should create a class to store your data and implement Comparable or use a Comparator.
public class Data { // Implement Comparable...
private String s;
private int n1;
private int n2;
// Implement constructors, getters, setters based on what you need...
// Implement compareTo (+ equals + hashCode) unless your going with Comparator
}
Then use a Collection that implements SortedSet to store your data, TreeSet is a good choice. The objects in the SortedSet are stored by reference so if you modify a value set in a local variable it will be modified in the collection as well.
Edit: If I understood your question about reference based lists correctly the following is possible in Java.
List<Data> dataList = // Create list and add data into it.
Data data = dataList.get(4);
data.setS(103); // Modifies S in the local data-object and in dataList because they are reference based.
It sounds like you already have a data structure to store your two int values and a string (since you have them sorted in an array list). You can include this data structure in a "tree node". A node typically has a reference pointer to a parent node (unless it is the root node) and 2 child nodes.
Since you want the tree to be sorted what you're really after is a special form of binary tree called a heap. The link to the Binary Heap wikipedia page below has an algorithm to show how to sort a binary heap.
http://en.wikipedia.org/wiki/Binary_heap
Here's some more general information on heaps and trees.
http://en.wikipedia.org/wiki/Binary_tree
http://en.wikipedia.org/wiki/Heap_(data_structure)
EDIT: You don't have to use a literal tree structure to store the your data in a tree form. It is perfectly acceptable to build a tree using an array. Instead of using reference pointers (parent and 1 or 2 child nodes) you can compute an index into the array. Each set of children is considered a "row" in the tree. The root element is on the zero row. It's two children are on the first row. The children of the root's children are on the second row, and so on.
Using this pattern the children of any node can be found using array[2*n+1] and array[2*n+2] where n is the row of the parent node. The parent of any node can be found by using array[floor( (n-1)/2)].