Sorted Doubly Linked List Java - java

I got a problem here, implementing a Sorted Doubly Linked List of first and last names.
Add a field to each link that indicates the alphabetically next first name; the existing next link is used to indicate the alphabetically next last name. You will also need a second root link for the list - the existing root link indicates the alphabetically first last name, and you will need one indicating the alphabetically first first name. Note that you will still only have one link object for each name entered in the list.
Having done this, make any necessary changes to your insert, lookup, and delete methods so that both interleaved lists are maintained. Also update the runtime estimates as required to remain accurate.
Finally, add a second lookup method that takes in a first name and returns all full names including that first name, and a second display method that prints the list of names out alphabetically by first name. Make sure you give runtime estimates for these methods as well.
And I am at a complete loss as how to do this. I already created a single linked list, with a first and last name, but that's as far as I was able to get.
Any Help would be great :D
Thank you.

Create a Link Class that has two link fields (nextFirstName, nextLastName) and a field for the Name Object.
On insert, first search the Link object that comes before (LastName) this new one and insert it after that using the nextLastName field. Then do the same with the FirstName, using the nextFirstName field as the link.
?????
profit!
This does smell a lot like homework :)

Because you have already implemented a Singly Linked List, expanding to a doubly linked list shouldn't be too difficult. You already have references going forward (see picture below). Now you need to add references going backward as well. In addition, note the blue lines in the picture below. Add additional references for the spelling properties. So each node will have the variables:
private Node NextFirstName;
private Node PreviousFirstName;
private Node NextLastName;
private Node PreviousLastName;

You do NOT need backward-references! The task asks for something like 2 single-linked Lists, that use the same objects as entrys. Every object has two links: one to the next item in list A, and one to the next item in list B.

Related

How to remove nodes at the start of a linked list?

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.

Why do i separate List and Node class?

Let me ask this question taking Java code mentioned in the query link.
In the same query link, a supplementary answer says: "In general, we need to separate List and Node classes, your List should have an head and your Node will have item and next pointer."
In addition, my class lecture says, there are two reasons for separating List and Node class.
Reason 1:
Assume user X and user Y are pointing to the first List_Node in that list
After adding soap item by user X in the shopping list, below is the situation,
So, User Y is inconsistent with this situation.
Reason 2:
Handling empty list.
user X pointing to an empty list, that mean X is null.
X.nth(1); //Null pointer exception
My question:
Reason_1 could have been handled by inserting new node after last node. Reason_2 could have been handled, as part of error check in the code.
So, Why exactly we need to separate Node and List class?
Note: Java code has item of type intinstead of type Object that can accommodate strings. I did not want to change this code again.
Reason_1 could have been handled by inserting new node after last node.
But that is changing the problem. Lists are ordered. Adding an element before an existing element or after an existing element are different operations. The data structure must be able to handle both operations, otherwise it is not a proper list.
Reason_2 could have been handled, as part of error check in the code.
That wouldn't work. The code of your list abstraction can't handle the NPE. If you attempt to call x.nth(1) and x is null, the exception is thrown before you get into any of the code that implements the list. Therefore, the (hypothetical) error handling in the list code cannot be executed. (Java exception handling doesn't work like that ...)
And as you correctly point out in your comment, forcing code that uses a list to handle empty lists as a special case would be bad list API design.
In short, both of the reasons stated are valid. (IMO)
Here are some very good reasons:
Separate implementation from interface. Perhaps in the future someone will find a new perfectly good implementation of your life involving a row of carrier pigeons moving elements around. Should your client code have to update everything with methods flapWings and rewardPigeon instead of manipulating nodes? No! (More realistically, Java offers ArrayList and LinkedList IIRC).
It makes more sense. list.reverse() makes sense. node.reverse()... what? Does this change every other node recursively or not?
Speaking of that reverse method, if you implement it right now you can implement it in O(N). You know if you have an int orientation; that is 1 or -1, you can implement it in O(1)? But all subsequent operations need to use that bit, so it's a meta-node operation, not a node operation.
Empty lists are possible. Empty nodes don't make sense. This is your (2). Imagine this: I am a client of your software. You have list == node. A rival vendor offers separation. You say "oh it works fine just add an error check in your code." Your rival does not. Who do I buy from? This is a thought experiment meant to convince you these really are different, and the former does have a defect.

Filter a list in Java

I have a list of people with additional information - let's say book rentals. So each Rental-object in my list would include a Person-object as an attribute and some rental information. For each person there will be 1..n entries in the list.
Now I need to filter this list based on some criteria. If ONE of the entries matches a certain criteria, I want to delete ALL entries for that person, even if the other entries do not match the criteria.
Is there a nice way to do this in one filter? Alternative would be to scan the list, identify people whose entries should be removed and then apply something like
Collections2.filter(myList, new MyPredicate(peopleIWantToRemove))
but I would like to do it with just one-time-list-traversal. How can I do this?
Going through the list twice (once to determine all the "bad" people, a second time to remove them) is, from an algorithm run-time standpoint, perfectly harmless. Whether you go through the list once or twice, the algorithm runs in O(n) time.
However, if you're really serious about only going through the list once, you could construct a temporary data structure that keeps track of all the places each person appears alongside a list of the people you want to get rid of.
Map<Person, List<Rental>> rentalsPerPerson;
List<People> badPeople;
When you parse the list the first time, you populate these two structures. Then you go through the list of badPeople, pull out their list of Rental objects, and purge those one at a time from your original list.
But honestly, that feels like a lot of bother for not much gain.
The way I'd recommend doing it? Go through the list twice. First pass: Compile a Set of bad people. Second pass: Create a new output List, initially empty. Go through your original List. For each element, if the Person isn't in the Bad set, add the entry to your output List.
Make the predicate stateful so that it not only matches if some criterion is met, but also if the person is known as a "bad" person.
Use Iterables.filter() instead. Per the class docs: "Unless otherwise noted, all of the iterables produced in this class are lazy, which means that their iterators only advance the backing iteration when absolutely necessary." That means you can compose multiple filters, but the traversal only happens once, when you do it yourself.
Sort list based on bad people criteria (bad entry first), and then filter using stateful predicate as C-Otto said
Now I need to filter this list based on some criteria. If ONE of the
entries matches a certain criteria, I want to delete ALL entries for
that person, even if the other entries do not match the criteria.
I think you were not doing filtering. because filtering return a subCollection (filtered) against on some condition. You are gonna always get the same Person List but with some element changed.
You want something like python's map(list, function). going through the list, for each person do something.
Guava's collections.transform can do it.
public static <F,T> Collection<T> transform(Collection<F> fromCollection,
Function<? super F,T> function)
check it out:
http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Collections2.html#transform(java.util.Collection, com.google.common.base.Function)

Java HashMap searching

As part of an ongoing class project, we were asked to implement Maps for better object linking.
In short, we currently have four arraylists which hold objects
// Array Lists used for sorting.
private static ArrayList<Party> partyList = new ArrayList<Party>();
private static ArrayList<Creature> creatureList = new ArrayList<Creature>();
private static ArrayList<Treasure> treasureList = new ArrayList<Treasure>();
private static ArrayList<Artifact> artifactList = new ArrayList<Artifact>();
Each class has their own fields (ie, Party has "index","name", Creature has "index", "name", "age", height", etc...but they all have a unique index)
This week we are to implement hashmaps, where the key of an object, is its index.
so, as an exmaple:
creatureMap.put(creature.index, creature)
...
Our program also allows searching. So i understand that now when we search by an index, we just search the appropriate hashmap for the index we want, and work with the object that is its value.
However, our program also allows the user to search by name, height, weight, etc. So, how are hashmaps being used efficiently here if it only helps when searching by index? What happens if i want to search a creature by name? I would have to loop through every value in the hashmap, look at its 'name' field..which is exactly what i am doing with the arraylist.
Our professor said this when someone asked a similar question:
The idea is that in the first project, the simple approach was to
insert all items into array lists and when one needed to link a
creature to a party, or an item to a creature, one would have to
search the ArrayList linearly until the index of the item was found.
This is O(n) operation if the ArrayList is not sorted, and an O(log n)
operation if the list is sorted, but the sorting is typically O(n*n)
or O(n log n) depending on the sorting operation used.
This week, I am asking you to implement an O(1) searching system based
on a map data structure. Thus, we should use the index of a item as
its key to generate the links. This is used once during processing of
the input file.
Thus, I am not sure i am understanding the concept of Maps / key-value pairs correctly.
Your understanding is correct: if your key is an index, you can only use the map to efficiently lookup by index. If you wanted to search by name, then you would have to key on the name.
I'm not too sure on what your professor meant by this:
Thus, we should use the index of a item as its key to generate the links.
(I think he refers to linking objects by index, as in "link a creature to a party" - maybe he did not refer to the use of hashmaps for searching)
On a side note, it's good practice to declare variables based on interfaces rather than concrete types. In your example, you should define your list fields as List instead of ArrayList:
private static List<Party> partyList = new ArrayList<Party>();
Running through your questions (and statements) in order....
So i understand that now when we search by an index, we just search
the appropriate hashmap for the index we want, and work with the
object that is its value.
That is correct.
However, our program also allows the user to search by name, height, weight, etc. So, how are hashmaps being used efficiently here if it only helps when searching by index?
If your hashmap is only storing by index then you are correct that it does not help you search by any other field. You could create a map for those fields also, but I don't think that's what your professor want (see below)
What happens if i want to search a creature by name? I would have to loop through every value in the hashmap, look at its 'name' field..which is exactly what i am doing with the arraylist.
Yes, if you needed to search by name, then you would use the values() method and iterate through that, checking each item.
when one needed to link a creature to a party, or an item to a creature, one would have to search the ArrayList linearly until the index of the item was found
...
Thus, we should use the index of a item as its key to generate the links. This is used once during processing of the input file.
This suggests to me that there is another part of the assignment - something to do with reading input from a file, and linking parties, creatures and items together.
I assume that input file for the parties refers to the creatures by index (and likewise for the creatures referring to items).
It is that linkage that the professor wants you to speed up by using these hashmaps.
I don't think he is trying to get you to change the way other sorts of searching works
(Obviously this is a guess since I don't know what the assignment actually says)

Question about linked lists in Java

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).

Categories