Java Lab 2: Linked Lists Begin with the linked list package linked to the course
ID: 3745120 • Letter: J
Question
Java
Lab 2: Linked Lists
Begin with the linked list package linked to the course web page (links section). The existing code is designed to avoid cycles.
Add a method public void addToCreateCycle(Node<T> nodeToAdd) that allows the user to add a Node in a way that will create a cycle.
Write JUnit tests that create a) a list with no nodes; b) a list with nodes but no cycles; c) a list with only one node with its next reference set to itself; d) a list with a cycle whose length (number of nodes involved in the cycle) is odd; e) a list with a cycle whose length is even. The tests should use assertions to determine whether each list contains a cycle. You do not need to determine where the cycle begins, only whether there is a cycle.
Turn in the unchanged Node.java file, the edited SinglyLinkedList.java file, and your JUnit tests.
We just learned the generics, and linked lists, can anyone help for this?
Explanation / Answer
struct node
{
int data;
struct node* next;
}
part a and c) public void addtoCreateCycle(struct node *last, int data)
{
//this function is only for no nodes(if the list is empty,last pointer will be Null)
if(last!=Null)
return last;
// Creating a node dynamically.
struct Node *last = (struct Node*)malloc(sizeof(struct Node));
// Assigning the data.
last -> data = data;
// list was empty. We link single node to itself
last -> next = last;
return last;
}
//This function returns true if given linked list is circular or not
part b) int isCircular(struct Node *head)
{
// for an empty linked list is circular
if (head == NULL)
return true;
// Next of head
struct Node *node = head->next;
// This loop would stop in both cases if it is circular or not
while (node != NULL && node != head)
node = node->next;
// If loop stopped because of circular condition
return (node == head);
}
part d and e) odd and even circular list
int countNodes(struct Node* head)
{
struct Node* temp = head;
int result = 0;
if (head != NULL) {
do {
temp = temp->next;
result++;
} while (temp != head);
}
if(result %2 == 0)
{
printf("Even ");
}
else
{
printf("Odd ");
}
return result; //print the value
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.