Why won't my linked list add nodes? (Java) - java

I'm trying to add a new Node to the end of my linked list but it doesn't seem to be doing anything. It adds the first element because it's a special case but then ignores all of the other assignments when I step through the debugging.
Here's the test I'm running:
#Test
public void testInsertElement()
{
PriorityList<String> list = new LinkedPriorityList<String>();
list.insertElementAt(0, "first");
list.insertElementAt(1, "second");
list.insertElementAt(2, "third");
assertEquals("first" , list.getElementAt(0));
assertEquals("second", list.getElementAt(1));
assertEquals("third" , list.getElementAt(2));
}
It fails on the second assertion because nothing is added after the first.
Here's the constructor for the Node Objects:
public class LinkedPriorityList<E> implements PriorityList<E> {
private class Node
{
private E data;
private Node next;
public Node(E element)
{
data = element;
next = null;
}
}
And finally the code that is failing on me:
public void insertElementAt(int index, E element) throws IllegalArgumentException
{
if(index>size() || index<0) //can only be between 0 and size()
throw new IllegalArgumentException();
if(size()==0)
first = new Node(element); //adding the first element. This works
else
{
if(index == size()) //if an element is being added to the end
{
Node ref = first; //assigning ref to the first element of the list
for(;ref!=null; ref = ref.next); //stepping through the list until ref is null
ref = new Node(element); //assigning the null reference a new Node. Doesn't assign
}
else //if an element is being inserted in the list. untested...
{
Node ref = first;
Node temp = new Node(element);
for(int i=1; i<index; i++)
ref = ref.next;
temp = ref.next;
ref = temp;
}
}
size++; //keeping track of how many elements in list
}
I think this works but if you want the get method too, here it is:
public E getElementAt(int index) throws IllegalArgumentException
{
if(index>=size() || index<0)
throw new IllegalArgumentException();
Node ref = first;
for(int i=0; i<index; i++)
ref = ref.next;
return ref.data;
}

When index == size, you want to create a new node, find the last node in the list, and assign the new node to its next pointer.
The last node is the one whose next pointer is null.
This should be enough to let you implement the algorithm by yourself.

This is probably what you meant to do:
for(; ref.next != null; ref = ref.next) {
/* intentionally empty */
}
ref.next = new Node(element);
Note that I'm both testing and assigning ref.next, not ref itself.

You need a temp node when adding at the end too (to keep track of the last element)
if (index == size())
{
Node ref = first, temp = first;
for (; ref != null; temp = ref, ref = ref.next);
temp.next = new Node(element);
}
By just assigning the new Node to ref; it doesn't link it to the current last node's next.

Related

Add method java

I want to add a method add(int index, E element) in Java, that inserts a specified element at a specified index in the list and shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices). But I guess something is wrong with the indices in my code in the for-loop. Any ideas how to solve it?
public class SingleLinkedList<E> implements ISingleLinkedList<E> {
Node head;
int size = 0;
#Override
public void add(int index, E element) throws IndexOutOfBoundsException {
Node newNode = new Node(element);
if(head == null && index == 0) {
head = newNode;
}
else if (index == 0 && head != null) {
Node tempNode = new Node(element);
tempNode.setmNextNode(head);
head = tempNode;
}
else {
Node tempNode = head;
for(int i = 1; i<index; i++) {
tempNode = tempNode.getmNextNode();
}
/**Node newNode = new Node(element);**/
newNode.setmNextNode(tempNode);
tempNode.setmNextNode(newNode);
}
size++;
}
}
My code for the Node class is:
public class Node<E> {
private E mElement;
private Node<E> mNextNode;
Node(E data) {
this.setmElement(data);
}
public E getmElement() {
return this.mElement;
}
public void setmElement(E element) {
this.mElement = element;
}
public Node<E> getmNextNode()
{
return this.mNextNode;
}
public void setmNextNode(Node<E> node)
{
this.mNextNode = node;
}
The problem is that I have a JUnit test that fails when adding this method and I do not know what more I need to add in order to pass the test.
#Test
public void testAddWithIndexesToListWith5Elements() {
int listSize = 5;
// First create an ArrayList with string elements that constitutes the test data
ArrayList<Object> arrayOfTestData = generateArrayOfTestData(listSize);
// Then create a single linked list consisting of the elements of the ArrayList
ISingleLinkedList<Object> sll = createSingleLinkedListOfTestData(arrayOfTestData);
// Add new elements first, in the middle and last to the ArrayList of test data
// and the single linked list
try {
arrayOfTestData.add(0, 42);
arrayOfTestData.add(3, "addedElement1");
arrayOfTestData.add(7, "addedElement2");
sll.add(0, 42);
sll.add(3, "addedElement1");
sll.add(7, "addedElement2");
}
catch (Exception e) {
fail("testAddWithIndexesToListWith5Elements - add() method failed");
}
// Check that the contents are equal
for (int i = 0; i < sll.size(); i++) {
assertEquals(arrayOfTestData.get(i), sll.get(i));
}
}
newNode.setmNextNode(tempNode);
tempNode.setmNextNode(newNode);
This is just going to create a cycle. It looks like your newNode should point to tempNode.getmNextNode() or something along those lines.
Your question is pretty unclear but I think I can see a problem.
If index is not 0, the you will iterate through the nodes until the index is reached.
If there are not enough elements in the list, you will reach the end of the list before the index where you want to insert the element.
In this case,
tempNode = tempNode.getmNextNode();
will set tempNode to null.
In the next iteration, this line will throw a NullPointerException.
You can bypass this issue by testing if tempNode.getmNextNode(); is null.
If that is the case, the element will just be inserted at the end/that point or will not be inserted.

Will my Circular LinkedList work correctly?

So I am currently trying to create a circle linked list (double linked list with each value having a previous, and a next value not equal to null), and I am not sure if I am properly creating it. My goal is to be able to create a LinkedList of values, and then when I iterate through the list, hasNext() should always return true (no null values). I think there is something wrong with the way I am adding values, but I am not sure. Here is the code, with the CircularList class having an inner node class:
public class CircularList<E> {
//I decided to still have heads and tails, to link them together
private Node<E> first = null;
private Node<E> last = null;
private Node<E> temp;
private int size;
//inner node class
private static class Node<E>{ //In this case I am using String nodes
private E data; //matching the example in the book, this is the data of the node
private Node<E> next; //next value
private Node<E> prev; //previous value
//Node constructors, also since in this case this is a circular linked list there should be no null values for previous and next
private Node(E data, Node<E> next, Node<E> prev){
this.data = data;
this.next = next;
this.prev = prev;
}
}
//end of inner node class
public void addValue(E item){
Node<E> n = new Node<E>(item, first, last);
if(emptyList() == true){ //if the list is empty
//only one value in the list
first = n;
last = n;
}
else{ //if the list has at least one value already
temp = first;
first = n;
first.next = temp;
last.next = first;
}
size++;
}
public boolean emptyList(){
boolean result = false;
if(first == null && last == null){ //if there is no values at all
result = true;
}
return result;
}
}
Just did a quick scan but this is the bit where it goes wrong:
Node<E> n = new Node<E>(item, first, last);
if(emptyList() == true) {
//if the list is empty
//only one value in the list
first = n;
last = n;
}
The prev and next item inside node are still null here. You should set those too.
else {
//if the list has at least one value already
temp = first;
first = n;
first.next = temp;
last.next = first;
}
Additionally you're not updating prev here.
Also consider using a linked list internally as a backing data structure rather then your own node structure. Then you only have to create the circular iterator.

Sorted Linked Based List Java

I'm working on an assignment for my Data Structures class. We have to create an address book using our own sorted linked based list adt. Right now the add method works, but it seems to make all the nodes point to the first node. Whenever I try to output the the list using getEntry() in a for loop, it gives me the last added entry each time. I've tried using toArray but it does the same thing. Can you see any problems?
public class GTSortedLinkedBasedList implements GTListADTInterface {
private Node firstNode;
private int numberOfEntries;
public GTSortedLinkedBasedList(){
//firstNode = new Node(null);
numberOfEntries = 0;
}
public void setNumberOfEntries(int x){
numberOfEntries = x;
}
public void add(ExtPersonType newEntry){
//firstNode = null;
Node newNode = new Node(newEntry);
Node nodeBefore = getNodeBefore(newEntry);
if (isEmpty() || (nodeBefore == null))
{
// Add at beginning
newNode.setNextNode(firstNode);
firstNode = newNode;
}
else
{
// Add after nodeBefore
Node nodeAfter = nodeBefore.getNextNode();
newNode.setNextNode(nodeAfter);
nodeBefore.setNextNode(newNode);
} // end if
numberOfEntries++;
}
private Node getNodeBefore(ExtPersonType anEntry){
Node currentNode = getFirstNode();
Node nodeBefore = null;
while ((currentNode != null) &&
(anEntry.getFirstName().compareTo(currentNode.getData().getFirstName()) > 0))
{
nodeBefore = currentNode;
currentNode = currentNode.getNextNode();
} // end while
return nodeBefore;
}
private class Node {
private ExtPersonType data;
private Node next;
public Node(ExtPersonType dataValue) {
next = null;
data = dataValue;
}
public Node(ExtPersonType dataValue, Node nextValue) {
next = nextValue;
data = dataValue;
}
public ExtPersonType getData(){
return data;
}
public void setData(ExtPersonType newData){
data = newData;
}
public Node getNextNode(){
return next;
}
public void setNextNode(Node newNode){
next = newNode;
}
}
public ExtPersonType getEntry(int givenPosition) {
if ((givenPosition >= 1) && (givenPosition <= numberOfEntries)){
assert !isEmpty();
return getNodeAt(givenPosition).getData();
}
else{
throw new IndexOutOfBoundsException("Illegal position given to getEntry operation.");
}
}
public void loadData(GTSortedLinkedBasedList contacts) throws FileNotFoundException{
//int index = 0;
ExtPersonType person = new ExtPersonType();
DateType tempDate = new DateType();
AddressType tempAddress = new AddressType();
Scanner file = new Scanner(new FileInputStream("Programming Assignment 1 Data.txt"));
while(file.hasNext()){
person.setFirstName(file.next());
person.setLastName(file.next());
tempDate.setMonth(file.nextInt());
tempDate.setDay(file.nextInt());
tempDate.setYear(file.nextInt());
person.setDOB(tempDate);
tempAddress.setStreetAddress(file.nextLine());
if(tempAddress.getStreetAddress().isEmpty()){
tempAddress.setStreetAddress(file.nextLine());
}
tempAddress.setCity(file.nextLine());
tempAddress.setState(file.nextLine());
tempAddress.setZipCode(file.nextLine());
person.setAddress(tempAddress);
person.setPhoneNumber(file.nextLine());
person.setPersonStatus(file.nextLine());
if(person.getPersonStatus().isEmpty()){
person.setPersonStatus(file.nextLine());
}
contacts.add(person);
System.out.println(contacts.getEntry(contacts.getLength()).getFirstName());
//index++;
}
}
public static void main(String[] args) throws FileNotFoundException {
AddressBook ab = new AddressBook();
ab.loadData(ab);
ExtPersonType people = new ExtPersonType();
//people = ab.toArray(people);
System.out.println(ab.getLength());
for(int cnt = 1; cnt <= ab.getLength(); cnt++){
people = ab.getEntry(cnt);
System.out.println(people.getFirstName());
}
}
EDIT: The add method is overwriting each previous object with the newly added one. It also doesn't seem to matter if I do a sorted list or just a basic list.
I'm not going to lie here, I'm not totally sure I understand your code but I think I see what's wrong. In your getNodeBefore() method's code, you set currentNode() always to firstNode(). I believe that is causing the problem. I see that you are trying to recursively move through the list to find the proper node but I don't think each recursive call is causing movement through the list. I suggest you add properties to the object that represent the forward and backward nodes.
Something like this...
private T data;
private Node nodeBefore;
private Node nodeAfter;
As you create objects, you assign the properties before and after and then all the information you need is contained in the object itself.
To move recursively through the list you would then just add a statement like currentNode = currentNode.nodeAfter.
Your getNodeBefore() method would simply return currentNode.nodeBefore and getNodeAfter() would return currentNode.nodeAfter.
You don't have code that handles the situation where the node being added will be the first node in the list, but the list is also not empty. In this case, getNodeBefore returns null, and your code overwrites the root node.
Try
if (isEmpty() && (nodeBefore == null))
{
// Add at beginning
newNode.setNextNode(firstNode);
firstNode = newNode;
}
else if(nodeBefore == null)
{
Node temp = new Node();
temp.setNextNode(first.next);
temp.setData(first.data);
newNode.setNextNode(temp);
firstNode = newNode;
}

Add node to end of Linked List

Having a bit of trouble adding a node to the end of my linked list. It only seems to display the very last one I added before I call my addFirst method. To me it looks like on the addLast method I'm trying to first create the node to assign it 5, then for the following numbers use a while loop to assign them to the last node on the linked list. Little stuck on why I can't get my output to display 5 and 6.
class LinkedList
{
private class Node
{
private Node link;
private int x;
}
//----------------------------------
private Node first = null;
//----------------------------------
public void addFirst(int d)
{
Node newNode = new Node();
newNode.x = d;
newNode.link = first;
first = newNode;
}
//----------------------------------
public void addLast(int d)
{
first = new Node();
if (first == null)
{
first = first.link;
}
Node newLast = new Node();
while (first.link != null)
{
first = first.link;
}
newLast.x = d;
first.link = newLast;
first = newLast;
}
//----------------------------------
public void traverse()
{
Node p = first;
while (p != null)
{
System.out.println(p.x);
p = p.link;
}
}
}
//==============================================
class test123
{
public static void main(String[] args)
{
LinkedList list = new LinkedList();
list.addLast(5);
list.addLast(6);
list.addLast(7);
list.addFirst(1);
list.addFirst(2);
list.addFirst(3);
System.out.println("Numbers on list");
list.traverse();
}
}
I've also tried creating a last Node and in the traverse method using a separate loop to traverse the last node. I end up with the same output!
public void addLast(int d)
{
Node newLast = new Node();
while (last.link != null)
{
last = newLast.link;
}
newLast.x = d;
newLast.link = last;
last = newLast;
}
The logic of your addLast method was wrong. Your method was reassigning first with every call the logic falls apart from that point forward. This method will create the Node for last and if the list is empty simply assign first to the new node last. If first is not null it will traverse the list until it finds a Node with a null link and make the assignment for that Nodes link.
public void addLast(int d) {
Node last = new Node();
last.x = d;
Node node = first;
if (first == null) {
first = last;
} else {
while (node.link != null) {
node = node.link;
}
node.link = last;
}
}
Your addLast() method displays the value of the last node because every time you append a node to the end of your list, you are overwriting the reference to "first". You are also doing this when you assign a new reference to first in the following line:
first = new Node();
Try the following:
public void addLast(int d)
{
Node newLast = new Node();
if (first == null)
{
newLast.x = d;
first = newLast;
return;
}
Node curr = first;
while (curr.link != null)
{
curr = curr.link;
}
newLast.x = d;
curr.link = newLast;
}
The method creates a new node and it is added to the end of the list after checking two conditions:
1.) If first is null: in this case the list is empty and the first node should be
initialized to the new node you are creating, then it will return (or you could do
an if-else).
2.) If first is not null: If the list is not empty you'll loop through your list until you
end up with a reference to the last node, after which you will set its next node to the
one you just created.
If you wanted to keep track of the tail of your list called "last", like you mentioned above, then add:
last = newLast
at the end of your method. Hope this helps!

Duplicate a LinkedList with a pointer to a random node apart from the next node

Q: Every node of the linked list has a random pointer (in addition to the next pointer) which could randomly point to another node or be null. How would you duplicate such a linkedlist?
A: Here's what I have, I just wanted to ratify if this was the optimal way of doing it.
Since there's no space constraints specified, I'm going to use a LinkedHashSet and a LinkedHashMap (I can imagine people nodding their head in disagreement already ;) )
First Iteration: Do the obvious - read each node from the list to be copied and create nodes on the new list. Then, read the random node like so: this.random.data and insert into the LinkedHashSet.
Second Iteration: Iterate through the new list and add each node's data as the first column and the node itself as the second column into the LinkedHashMap (doesn't have to be Linked, but I'm just going with the flow).
Third Iteration: Iterate over the LinkedHashSet (this is the reason why this needs to be Linked - predictable ordering) and the new list simultaneously. For the first node, read the first entry of the LinkedHashSet, look up the corresponding object in the LinkedHashMap and add as the random node to the current node in the new list.
3 iterations does seem a little crazy, but the attempt was to keep the complexity as O(N). Any solution that improves on the O(3N) space requirement and O(3N) runtime complexity would be great. Thanks!
Edit: The entry from the LinkedHashSet can be removed when making an entry into the LinkedHashMap, so this would only take O(2N) space.
As pointed out by MahlerFive, I think you can do this with O(2N) runtime complexity, and O(N) space complexity.
Let's assume you have
public class Node {
private Node next;
private Node random;
private String data;
// getters and setters omitted for the sake of brevity
}
I would do a deep copy of a linked list of Nodes as:
private Node deepCopy(Node original) {
// We use the following map to associate newly created instances
// of Node with the instances of Node in the original list
Map<Node, Node> map = new HashMap<Node, Node>();
// We scan the original list and for each Node x we create a new
// Node y whose data is a copy of x's data, then we store the
// couple (x,y) in map using x as a key. Note that during this
// scan we set y.next and y.random to null: we'll fix them in
// the next scan
Node x = original;
while (x != null) {
Node y = new Node();
y.setData(new String(x.getData()));
y.setNext(null);
y.setRandom(null);
map.put(x, y);
x = x.getNext();
}
// Now for each Node x in the original list we have a copy y
// stored in our map. We scan again the original list and
// we set the pointers buildings the new list
x = original;
while (x != null) {
// we get the node y corresponding to x from the map
Node y = map.get(x);
// let x' = x.next; y' = map.get(x') is the new node
// corresponding to x'; so we can set y.next = y'
y.setNext(map.get(x.getNext()));
// let x'' = x.random; y'' = map.get(x'') is the new
// node corresponding to x''; so we can set y.random = y''
y.setRandom(map.get(x.getRandom()));
x = x.getNext();
}
// finally we return the head of the new list, that is the Node y
// in the map corresponding to the Node original
return map.get(original);
}
Edit: I found that this question is a duplicate of the one asked here: there you find an answer that shows how to solve this problem in O(3N) runtime complexity with no extra space: very ingenious! But it uses a trick with C pointers, and I'm not sure how to do the same in java.
You can do this with 2N steps and a map with N elements.
Walk the old list following the 'next' pointers. For each node you visit, add a node to your new list, connect the previous node in your new list to the new node, store the old node random pointer in the new new node, then store a mapping of the old node pointer to the new node pointer in a map.
Walk the new list, and for each random pointer, look it up in the map to find the associated node in the new list to replace it with.
I too was asked this question in interview recently.
Here is what i proposed.
Create a map of original list nodes where addreess of each node will be key and the offset of random pointer will be the value.
Now create a new linked list with random pointer =null from the original map.
In the end, iterate through the original list , with the help of map get offset of original pointer and use that offset to link random pointer in newly created map.
Interviewer was not happy in the end.May be looking for some better approach or he had the set answer in his mind and unable to grasp new way of solving it.
in O(n) time and with constant space
public class CloneLinkedListWithRandomPointer {
public static void main(String[] args) throws Exception {
SpecialLink link = new SpecialLink(1);
SpecialLink two = new SpecialLink(2);
SpecialLink three = new SpecialLink(3);
SpecialLink four = new SpecialLink(4);
SpecialLink five = new SpecialLink(5);
link.next = two;
two.next = three;
three.next = four;
four.next = five;
link.random = four;
two.random = five;
three.random = null;
four.random = five;
five.random=link;
SpecialLink copy = cloneSpecialLinkedList(link);
System.out.println(link);
System.out.println(copy);
}
public static SpecialLink cloneSpecialLinkedList(SpecialLink link) throws Exception{
SpecialLink temp = link;
while(temp != null){
temp.next = (SpecialLink) temp.clone();
temp = temp.next==null?temp.next:temp.next.next;
}
temp = link;
while(temp != null){
temp.next.random = temp.random!=null?temp.random.next:null;
temp = temp.next==null?temp.next:temp.next.next;
}
SpecialLink copy = link.next;
temp = link;
SpecialLink copyTemp = copy;
while(temp.next!= null && copyTemp.next != null){
temp.next = temp.next.next;
copyTemp.next = copyTemp.next.next;
temp = temp.next;
copyTemp = copyTemp.next;
}
return copy;
}
}
class SpecialLink implements Cloneable{
enum Type{
ORIGINAL,COPY
}
int val;
SpecialLink next;
SpecialLink random;
Type type;
public void setValue(int value){
this.val = value;
}
public SpecialLink addNode(int value){
return next = new SpecialLink(value);
}
public SpecialLink(int value) {
super();
this.val = value;
this.type = Type.ORIGINAL;
}
#Override
public String toString() {
SpecialLink temp = this;
StringBuilder builder = new StringBuilder();
while(temp != null){
builder.append(temp.val).append("--").append(temp.type.toString()).append("->").append(temp.random == null? null:temp.random.val).append("--").append(temp.random == null? null:temp.random.type);
builder.append(", ");
temp = temp.next;
}
return builder.toString();
}
#Override
public Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
SpecialLink clone = (SpecialLink) super.clone();
clone.type = Type.COPY;
return clone;
}
}
Walk the list and use clone()?
I wrote code for #MahlerFive 's solution, which works without mapping.
Here's the code:
private static class Node {
private String item;
private Node next;
private Node random;
}
public static Node cloneLinkedStructure(Node head) {
// make holes after each original node
for (Node p = head; p != null;) {
Node pnext = p.next;
Node hole = new Node();
hole.item = ".";
p.next = hole;
hole.next = pnext;
p = pnext;
}
Node fakeHead = new Node(); // fake new head
Node q = fakeHead;
Node p = head;
while (p != null) {
// build the new linked structure
Node oldq = q;
q = new Node();
q.item = p.item;
oldq.next = q;
q.random = p.random.next; // link to a hole
Node hole = p.next;
hole.random = q; // use link RANDOM as a backward link to new node
p = hole.next;
}
q.next = null;
Node newHead = fakeHead.next; // throw fake head
// build random links for the new linked structure
for (q = newHead; q != null; q = q.next)
q.random = q.random.random;
// delete holes to restore original linked structure
for (p = head; p != null; p = p.next)
p.next = p.next.next;
return newHead;
}
1) Create the copy of node 1 and insert it between node 1 & node 2 in original Linked List, create the copy of 2 and insert it between 2 & 3.. Continue in this fashion, add the copy of N afte the Nth node
2) Now copy the arbitrary link in this fashion
original->next->arbitrary = original->arbitrary->next; /*TRAVERSE TWO NODES*/
This works because original->next is nothing but copy of original and Original->arbitrary-> next is nothing but copy of arbitrary.
3) Now restore the original and copy linked lists in this fashion in a single loop.
original->next = original->next->next;
copy->next = copy->next->next;
4) Make sure that last element of original->next is NULL.
Time Complexity: O(n)
Auxiliary Space: O(1)
source
Here is the Java implementation:
public static <T> RandomLinearNode<T> clone(RandomLinearNode<T> head) {
if (head == null) {
return head;
}
RandomLinearNode<T> itr = head, temp;
// insert copy nodes after each original nodes
while (itr != null) {
temp = new RandomLinearNode<T>(itr.getElement());
temp.next(itr.next());
itr.next(temp);
itr = temp.next();
}
// copy the random pointer
itr = head;
while (itr != null && itr.next() != null) {
if (itr.random() != null) {
itr.next().random(itr.random().next());
}
itr = itr.next().next();
}
// break the list into two
RandomLinearNode<T> newHead = head.next();
itr = head;
while (itr != null && itr.next() != null) {
temp = itr.next();
itr.next(temp.next());
itr = temp.next();
}
return newHead;
}
Here is the unit tests
#Test
public void cloneLinkeListWithRandomPointerTest() {
RandomLinearNode<Integer> one = new RandomLinearNode<Integer>(1, null, null);
RandomLinearNode<Integer> two = new RandomLinearNode<Integer>(2, one, null);
RandomLinearNode<Integer> three = new RandomLinearNode<Integer>(3, two, null);
RandomLinearNode<Integer> four = new RandomLinearNode<Integer>(4, three, null);
RandomLinearNode<Integer> five = new RandomLinearNode<Integer>(5, four, four);
RandomLinearNode<Integer> six = new RandomLinearNode<Integer>(6, five, two);
RandomLinearNode<Integer> seven = new RandomLinearNode<Integer>(7, six, three);
RandomLinearNode<Integer> eight = new RandomLinearNode<Integer>(8, seven, one);
RandomLinearNode<Integer> newHead = LinkedListUtil.clone(eight);
assertThat(eight, not(sameInstance(newHead)));
assertThat(newHead.getElement(), equalTo(eight.getElement()));
assertThat(newHead.random().getElement(), equalTo(eight.random().getElement()));
assertThat(newHead.next().getElement(), equalTo(eight.next().getElement()));
assertThat(newHead.next().random().getElement(), equalTo(eight.next().random().getElement()));
assertThat(newHead.next().next().getElement(), equalTo(eight.next().next().getElement()));
assertThat(newHead.next().next().random().getElement(), equalTo(eight.next().next().random().getElement()));
assertThat(newHead.next().next().next().getElement(), equalTo(eight.next().next().next().getElement()));
assertThat(newHead.next().next().next().random().getElement(), equalTo(eight.next().next().next().random().getElement()));
}

Categories