For this assignment, you will be completing several methods in a class named Lin
ID: 3698697 • Letter: F
Question
For this assignment, you will be completing several methods in a class named LinkedList java will fill in the implementation of the following methods using Nodes (you may use as a reference the LinkedList exercise we completed in class using java or C++): file. You getFirst0 addFirst(item) contains( item) set( int n, item) removeNthNode( int n) addNode(int n, item) removelast0 getL ast0) It is your task to implement each of the missing methods. The main) method in the LinkedL.ist java file instantiates a linked list that can hold Strings, but your code should work with any objects stored within the listExplanation / Answer
class Node {
int data;
Node *next=NULL;
};
class List{
Node *head;
List(){
head = new Node;
}
// Return first node in the list
Node * getFirst(){
return head;
}
// Add a new node in the beginning of the list
void addFirst(int item){
Node *newNode = new Node;
newNode->data = item;
newNode->next = head;
head = newNode;
}
// Search list
Node * contains(int item){
Node *current = head;
while(current->next){
if(current->data == item)
return current;
else {
current = current->next;
}
}
// If while loop exits without returning a pointer to Node implies item not present in the list
return NULL;
}
// Set data in nth node to item
void set(int n, int item){
int count = 1;
Node *current = head;
while(current->next && count != n){
current = current->next;
count++;
}
if(count == n)
current->data = item;
else
cout<<"Number of items in the list are less than "<<n<<endl;
}
// Add node at nth place in the list
void addNode(int n, int item){
int count = 1;
Node *current = head;
while(current->next && count != n-1){
current = current->next;
count++;
}
if(count == n-1){
Node *temp = new Node;
temp->data = item;
temp->next = current->next;
current->next = temp;
}
else
cout<<"Number of items in the list are less than "<<n<<endl;
}
// Get last node in the list
Node * getLast() {
Node *current = head;
while(current->next){
current = current->next;
}
return current;
}
// remove last node in the list
void removeLast() {
Node *current, *prev;
prev = head;
current = head->next;
if(head == NULL){
cout<<"List is empty"<<endl;
}else if(head->next == NULL){
free(head);
} else {
while(current->next){
prev = current;
current = current->next;
}
prev->next = NULL;
free(current);
}
}
// remove nth node in the list
void removeNthNode(int n){
Node *current, *prev;
prev = head;
current = head->next;
int count =2;
if(head == NULL){
cout<<"List is empty"<<endl;
}else if(n == 1){
Node *temp = head;
head = head->next;
free(temp);
} else {
while(current->next && count != n ){
prev = current;
current = current->next;
}
prev->next = current->next;
current->next = NULL;
free(current);
}
}
};
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.