C++ Please explain the code below. It doesn't have to be long, as long as you explain what the important parts of the code do. You can also explain it line by line for best ratings. Thank you so much! The code is already correct, only explanation needed void addTail(int num) { node* newest = create_node(num); if (tail != NULL) { tail->next = newest; } tail = newest; if (head == NULL) { head = newest; } index++; } int add(int num) { addTail(num); return index; } int get(int pos) { node* currnode = head; int count = 0; while (currnode != NULL){ count++; if (count == pos){ return currnode -> element; }else{ currnode = currnode -> next; } } return -1; } int size() { return index; } void swap(int pos1, int pos2) { int temp = NULL; node* currnode = head; node* Nodeprev1 = NULL; node* Nodeprev2 = NULL; node* node1 = head; node* node2 = head; while (currnode != NULL){ temp++; if (temp == pos1-1){ Nodeprev1 = currnode; node1 = Nodeprev1->next; } if (temp == pos2-1){ Nodeprev2 = currnode; node2 = Nodeprev2->next; if(node2->next == NULL){ tail = node1; } break; } currnode = currnode->next; } if (Nodeprev1 != NULL){ Nodeprev1->next = node2; }else{ head = node2; } Nodeprev2->next = node1; node* count = node2->next; node2->next = node1->next; node1->next = count; }
C++ Please explain the code below.
It doesn't have to be long, as long as you explain what the important parts of the code do. You can also explain it line by line for best ratings. Thank you so much! The code is already correct, only explanation needed
void addTail(int num) {
node* newest = create_node(num);
if (tail != NULL) {
tail->next = newest;
}
tail = newest;
if (head == NULL) {
head = newest;
}
index++;
}
int add(int num) {
addTail(num);
return index;
}
int get(int pos) {
node* currnode = head;
int count = 0;
while (currnode != NULL){
count++;
if (count == pos){
return currnode -> element;
}else{
currnode = currnode -> next;
}
}
return -1;
}
int size() {
return index;
}
void swap(int pos1, int pos2) {
int temp = NULL;
node* currnode = head;
node* Nodeprev1 = NULL;
node* Nodeprev2 = NULL;
node* node1 = head;
node* node2 = head;
while (currnode != NULL){
temp++;
if (temp == pos1-1){
Nodeprev1 = currnode;
node1 = Nodeprev1->next;
}
if (temp == pos2-1){
Nodeprev2 = currnode;
node2 = Nodeprev2->next;
if(node2->next == NULL){
tail = node1;
}
break;
}
currnode = currnode->next;
}
if (Nodeprev1 != NULL){
Nodeprev1->next = node2;
}else{
head = node2;
}
Nodeprev2->next = node1;
node* count = node2->next;
node2->next = node1->next;
node1->next = count;
}
Step by step
Solved in 2 steps