I went to interview today and this question got thrown at me. I can't come up with an answer.
the gig is
SList2 = SList1.clone();
if you change things in SList1 (e.g editing the object) it will not affect the similar object in SList2. I attempt it, I create new nodes but whenever I get to the cloning object part I failed. Was thinking about object.clone() but the question state that no built-in function is allowed.
Slist2.head = new Node();
Node newList = Slist2.head;
Node head = Slist1.head;
Slist.head.(all data) = head.(all data);
while(head.hasNext()){
head = head.next();
Node newGuy = newNode();
newNode.(all data) = node.(all data)
newList.next = newGuy;
}
This will follow through the old list, manually copying all data into a new node and tacking that node on to the new list
This is two problems disguised as one.
How would I read in the values from the linked list object, and
How would I create it in such a way that no references were reused (that is, I don't just reassign the head of one list to the head of the other)?
Without diving into code, let's look at this at a high level. Provided that your linked list can provide iteration (that is, it has an Iterator-like object that keeps its state in the list, and returns a node when next() is referenced), then the first problem becomes a matter of iterating over the linked list via the iterator.
From there, you would want to peel out the raw value from what you're iterating over, and add them into your new linked list object.
You're pretty much done then; nothing fancy needs to be worked out. It's literally taking data from one structure and inserting it into another.
Related
I have this list : [5,3,5,5,3,7,7,5,3,2]
and I need to remove every time I have a sequence in the list which is the same as a queue given to me - for example the queue [exit-5,3-enter] my function returns
[5,3,5,7,7,2-->null] but I want it to be [5,7,7,2-->null].
I would also like to mention that when I am talking about a linked list I actually mean a list of nodes-
Node<Integer> lis
(it has a value and a pointer to the next node). I already did the function I mentioned but what I did doesn't work if the sequence appears at the start of the list-like Iv'e already mentioned because I don't know how to remove from the start of the list. I know how to remove a node I just reference to next Nodes and leave it with no reference but my function gets a copy of the main reference to the list
public static void removeAppear(Node<Integer> n,Queue<Integer> q){
so if I would just write :
n=n.getNext();
for example it won't actually delete the first node, and from the void main method I would still see the first node. If you need the function I did say so but I really just need to know how to delete a first node.Sorry if it's a basic question but i'm quite new to programming.
You can’t mutate a linked list to remove leading nodes, unless you stop thinking of your function as ‘changing the list’ and start thinking of it as ‘returning a new list which is different from the original’. Then it can return a reference to a node which was not originally the first 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.
Is is possible for me to delete all nodes of my linkedlist to delete by my this code piece? If no then how is it possible to delete all the node at once!
my code is
EditNode mynode=start;
while(mynode!=null){
mynode.editnext=null;
mynode=mynode.editnext;
}
Help needed! Thanks in advance...
Your code dosen't work because you are setting mynode.editnext to null and then trying to reference it. So that's not going to work.
To delete all nodes in a linked list, in Java, just clear the head pointer. Java will garbage collect the rest.
start = null;
Please note that this answer is meant for your custom linked list. In production, you should use the Java implementation of LinkedList, which has a .clear() method on it. This is a much cleaner way to handle a list.
This is because you may have stray pointers which point to an item in the list, and this will keep a reference around to the rest of the list and prevent garbage collection. You shouldn't build organizational structure like the editnext property into the data structure. They should be separate classes.
To clear all of your pointers in each node, use the following code:
EditNode mynode;
while (start != null){
mynode = start.editnext;
start.editnext = null;
start = mynode;
}
Did you check clear() method of LinkedList?
public void clear() - Removes all of the elements from this list. The list will be empty after this call returns.
Lets say I have a list like this:
private LinkedList<String> messages = new LinkedList<String>();
When my method gets invoked for the first time there some strings added to this list. And I have also another method in which I need to clear this list from previously added values. To clear it I can use:
messages.clear();
This will remove all the elements from the list. Also I can create a new instance like this:
messages = new LinkedList<String>();
Which way is more proper to clear the list?
messages.clear();
Will actually clear the list, messages = new LinkedList<String>(); will just set messages as referencing a new list instance, so you could argue the first way is more "correct" to clear the list instance.
Say you have a list that is referenced by two variables, a and b. Like this (they don't have to be as close to eachother as this, they might even be in different files..):
final List<String> a = new LinkedList<String>();
final List<String> b = a;
Now, there is a big difference between
a.clear();
which will make both a and b reference the same, empty list, and
a = new LinkedList<String>();
which will make 'a' reference a new, empty list, and 'b' the old, populated list. (So they do not reference the same list).
Since you probably want them to reference the same list, a.clear() is preferred, since you won't get any surprises when your looking at the list referenced by b (which you might believe to be empty, but turns out to be populated if you use the new-approach).
I prefer the first approach i.e. messages.clear(); as it clear the elements but the List is not destroyed and recreated. All elements are removed as desired.
One side effect is there though: It iterates your list and removes one item at a time so if the list is huge then it's an unnecessary overhead.
for (Node<E> x = first; x != null; ) {
Node<E> next = x.next;
x.item = null;
x.next = null;
x.prev = null;
x = next;
}
first = last = null;
size = 0;
modCount++;
Same way second approach has also one side effect: If you are using the object reference of you r list somewhere else in your program, that needs to handled properly otherwise you could get some unwanted surprises e.g. if you added your list to some other object/variable, then first approach will clear that elements from every place where it was referenced while second will not.
Summary: Both the approach outcomes are different in low level nature; though they seem to to serve your high level requirement (clearing the list). Decide carefully based on your low level requirements.
They are almost similar, but I would say messages.clear() is more flexible.
The second approach is simple and much used, but the problem where you have final modifier on your list you can not clear it that way.
messages.clear();
is more efficient. For more safety you can ask if this list is not empty befor
Personnaly I prefere to use LinkedList#clear because it is more clearly to understand during reading the code what you are doing.
But the new LinkedList<String>(); will work fine as well. So it's up to you what to use!
It clearly depends upon your need.
If you want to keep reference to your list object instance (as an example if that clear method is called inside a method in which the messages is a parameter, then the call to .clear() is the best solution.
On the other hand, if the list you want to clear is a member field (or a local variable in a method) of the object the current method is a member of, then you can call new LinkedList<String>(); without any trouble.
Notice that, to avoid the first (which I tend to disapprove), i usuall always return obejcts I modify as results from methods modifying them.
the first one is preferable. the second one makes some extra burden on the garbage collector. but the first one not.
I have two classes:
Class Node {
int address
}
Class Link{
int latency;
int bandwidth;
Node node1;
Node node2;
}
public Link [] link= new Link[Nmax];
if I want to create a link between two nodes, it is easy, I've just to:
node1=new Node(); //and then I add parameter like address and so on
node2= new Node();//...............
link[1]= new Link();
link[1].node1=node1;
link[1].node2=node2;
link[1].latency=15; //and so on, we suppose that we have 100 nodes and 60 links
Now, during the program, sometimes we add some new nodes then we have to add links between them, I can do this with the same manner us above, my question is:
what I have to do if I want to delete a node ? (links between this node and other existing nodes must be deleted too)
--- Edited in response to jpm's excellent observation ---
In your case, you are doing all of the data structure management yourself, but are not storing enough infomation to undo the additions to the data structure.
You need to store enough information at create time to support the other operations on the data structure. This means that perhaps the choice of an array as your high-level exposed data structure is a bad choice, because there is no guarantee that additions will maintain the sufficient information to support the removals.
Wrap the array in an object, and write the code in the add(...) method to support the efficient removal. This probably means storing more information, which was constructed specifically for the support of removal.
--- Original post follows ---
To delete an object in Java, ensure that nothing "points" to it (has a reference to it) and then wait. Automatic garbage collection will do the deleting for you.
An example to make this clear
link[1] = new Link();
// now we have an extra Link in our array
link[1] = null;
// now garbage collection will delete the recently added Link object.
Note that if you have two or three references to the created Link object, it will not be collected until all the references are lost
link[1] = new Link();
// now we have an extra Link in our array
Link current = link[1];
// now we have two references to the newly created Link
link[1] = null;
// now we have one reference to the newly created Link
current = null;
// now the newly created Link is a candidate for garbage collection
The way this is implemented is there is a top-level Thread of the user implemented program. If that thread can reach the Object in question then it won't get garbage collected. This means that rings and meshes of Objects that are no longer reachable from the live Threads will be collected in mass.
before deleting a node; loop over your links and remove any that have your node to be deleted as node1 or node2, then delete your node.
You probably want to explore using a better data structure than an array for this use case. You want to be able to inspect all Links, figure out which ones refer to the deleted Node, and remove those Links. Start looking at List/Set and see if they suit your needs, and slowly evolve into a good implementation that gives you what you need.
"Deleting" an object in Java means to remove all references that point to the object. The Garbage Collector then eventually will free the memory occupied by the object. So what you need to do, would be to set all references to a specific Node object to null.
// lets delete node1
link[1].node1 = null;
node1 = null;
// at some point the object will be deleted