Storing objects in link lists - java

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;
}

Related

How to change the node in the built-in java LinkedList class to add a right and down pointer?

I have started to use Java. I want to use the built-in Java LinkedList class with my custom node class (my node class will contain fields: data, down pointer, right pointer). Is it possible to do so?
Here is my node class:
public class Node {
int data;
Node rt;
Node dw;
//constructor
public Node(int dataValue) {
rt=null;
dw=null;
data=dataValue;
}
//methods:
public int getData() {
return data;
}
public void setData(int dataValue) {
data = dataValue;
}
public void setrt(Node nextVal) {
rt=nextVal;
}
public void setdw(Node nextVal) {
dw=nextVal;
}
public Node getrt() {
return rt;
}
public Node getdw() {
return dw;
}
I created the following instance:
LinkedList h = new LinkedList<>();
I want to implement a 2D linked list using the built-in linked list class in java. To be able to do this i want to implement my custom node.
No, the node class of LinkedList is private, not exposed, you cannot access it. Except probably through some reflection hack.
And even if you could access the node class, you probably could not replace it with your own class. The LinkedList class is hardcoded to use its own node class.
If you really insisted, you could take the source code of the LinkedList class and modify it to use your node class. Please check if there are any license problems with such an approach before you do it, though. Also my gut feeling is that it’s not worth the trouble compared to writing your custom linked list class from scratch.
Java’s LinkedList is a doubly linked list, so each node has previous and next pointers and reference to data.
You can create a LinkedList of your own for this implementation.
But it looks like there are some basic things which you are doing wrong:
First, as per your implementation, you will be better off with Graph,
because what you are seeking is graph data structure, with each
vertex having four edges.
Second, you should not modify the existing data structures/collection
API provided by Java. If you really want to use different
data-structure, then create it and use it.
And the third and the most important thing to consider is that you
should always try to use the most efficient data-structures to solve a
problem. For example, you can create a 2-D Linkedlist, but ask
yourself, whether is it the most efficient one to store 2-D data? It
might happen that you could have used a matrix or a graph for storing the data.
Also, whenever you create or use a datastructure, consider whether
your application is read/write heavy, based on that you can optimize
storing and fetching of data.
But, it looks like you have just started, and so I would suggest just to go through basic data-structure books or online resources first.
You can also go through below URL which has similar requirement.
custom node class with java's linkedlist class

Redundant serialization of linked list and pointer into list

I have kind of a contrived question.
Let's say I have a linked list of users, and one of these users is "User of the week":
public class UserOfTheWeek implements Serializable {
private UserNode root;
private UserNode userOfTheWeek;
//...
private class UserNode {
String username;
UserNode next;
}
public void saveToFile() {
ObjectOutputStream oos = new ...
oos.writeObject(root);
oos.writeObject(userOfTheWeek);
}
}
root obviously stores a reference to the head of the list, and userOfTheWeek could point to any of the nodes. I want to save the linked list, but will saving the userOfTheWeek make a copy of a part of the list? If the user at the head of the list happens to be the user of the week, this could save the entire list twice, and worse, userOfTheWeek wouldn't point to an object in the list pointed at by root.
Does anyone know what will happen? And if not, I am also open to an alternate solution.
I want to save the linked list, but will saving the userOfTheWeek make a copy of a part of the list?
No.
If the user at the head of the list happens to be the user of the week, this could save the entire list twice
No.
The stream knows which objects have already been serialized to it, and doesn't reserialize them. See the Object Serialization Specification #1.2. Similarly, the object is only deserialized once. Object graphs can be serialized and recovered in full generality, including cycles.
and worse, userOfTheWeek wouldn't point to an object in the list pointed at by root.
You would have to serialize and deserialize that separately, but it won't result in creation of a new object, it will refer to an object in the list.

Creating a Node Class

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)

Java: how to use dummy node or mark a node as dummy node

A question asking you to delete the middle node in a linked list, only that node is give.
The way to solve the problem is copy middle.next.element to middle.element and then delete middle.next by doing middle.next=middle.next.next
There's a special case which is when middle.next is the last node.
The answer say that you could mark the middle node as dummy.
I'm not familiar with the idea "dummy". How to mark a node as dummy and how to use a dummy node in other cases?
What about dummy data in general?
There is no general answer to this question. The implementation of the linked list must already define the concept of a dummy node and use it consistently. A typical way to achieve this would be by declaring a special dummy instance:
public class Node {
public static final Object DUMMY = new Object();
...
and assigning middle.element = DUMMY;
As you can imagine, this will have no effect unless all the rest of the API implementation abides by this convention.
If your list is specified as unable to contain null elements, then you could also assign middle.element = null, but the rest of the story stays the same.

Which data structure to use for nodes in Java?

I want to create a class node, class Edge and class Graph. In class node, it must take some number as input to create nodes. Also, I want this class to have methods where I can change different attributes of the nodes. Also, it must contain a method to send and receive information from its adjacent nodes over Edge. These information receiving and sending methods should have provision to control information flow.
I am not sure which data structure to use for nodes to fulfill these requirements.
Create a class Node that has all the attributes that you want. Ex. If you want to create a Node for a binary Tree your Node class can be something like.
class Node
{
Node left;
Node right;
int info;
Node(int value)
{
this.info = value;
}
//Add more attributes or functionalities
}
This is one representation of how you can create a Node class. Depending upon your requirements the representation might change but the underlying concept remains the same.
Create your own class node.
A node is just an object. Give it some attributes (for your example you probably want weight and value).
public class Node{
private double weight;
private String value;
private ArrayList<Node> edges;
//setters and getters
}
Create a class Node which has a list of references to other Nodes (in a directed graph, this is especially usefull). An edge is not actually a "thing" to create - it's more like a connection.
The two most common ways to implement graphs are to use either an adjacency matrix or an adjacency list.
The matrix approach involves using a 2d array to determine if node i and node j are connected by asking if node[i][j] is true. Wasteful on space, but has constant time access.
Adjacency lists keep track of every adjacent node to the current node, which save on space but cost linear time in order to determine if a node is connected to it.
These articles explain it better:
Matrix
List

Categories