Objectives Implement insertion in a singly linked list Code
Objectives:
Implement insertion in a singly linked list.
Code so far:
#include<iostream>
using namespace std;
/*
* The convention for the list used here is that the head
* contains no information it is solely a pointer to the
* first element
*/
struct node {
int info;
struct node* link;
};
void printList(struct node *head) {
while (head != NULL) {
cout << head->info << \" \";
head = head->link;
}
cout << endl;
}
/*
* Inserts a new element into the linked list after the cursor.
*/
void insertAfter(struct node *cursor, int value) {
/* Finish me! */
}
int main(void) {
struct node head;
head.link = NULL;
struct node *current = &head;
for (int i = 0; i < 10; i++) {
insertAfter(current, i*i);
current = current->link;
}
current = &head;
for (int i = 11; i < 15; i++) {
insertAfter(current, i*i);
current = current->link;
}
struct node *cursor = head.link;
struct node *next;
while (cursor != NULL) {
cout << cursor->info << \" \";
next = cursor->link;
free(cursor);
cursor = next;
}
cout << endl;
return 0;
}
Question:
The provided code provides the declaration, not definition of insertAfter. Complete the function definition to produce the correct output below. Take care in handling the link to the next node when adding the current element.
Output:
121 144 169 196 0 1 4 9 16 25 36 49 64 81
Solution
#include<iostream>
#include <cstdlib>
using namespace std;
/*
* The convention for the list used here is that the head
* contains no information it is solely a pointer to the
* first element
*/
struct node {
int info;
struct node* link;
};
void printList(struct node *head) {
while (head != NULL) {
cout << head->info << \" \";
head = head->link;
}
cout << endl;
}
/*
* Inserts a new element into the linked list after the cursor.
*/
void insertAfter(struct node *cursor, int value) {/*1. check if the given cursor is NULL */
// if cursor is null then return
if (cursor == NULL)
{
cout<<\"the given cursor node cannot be NULL\";
return;
}
/* allocate memory to new node */
node* new_node =new node;
/*put in the value */
new_node->info = value;
/* Make link of new node as link of cursor */
new_node->link = cursor->link;
/* move the link of cursor as new_node */
cursor->link = new_node;
}
int main(void) {
struct node head;
head.link = NULL;
struct node *current = &head;
for (int i = 0; i < 10; i++) {
insertAfter(current, i*i);
current = current->link;
}
current = &head;
for (int i = 11; i < 15; i++) {
insertAfter(current, i*i);
current = current->link;
}
struct node *cursor = head.link;
struct node *next;
while (cursor != NULL) {
cout << cursor->info << \" \";
next = cursor->link;
free(cursor);
cursor = next;
}
cout << endl;
return 0;
}
--------------------output------------------------
121 144 169 196 0 1 4 9 16 25 36 49 64 81
-------------------output ends-------------------


