1. The numbers 5, 2, 7, 6 were inserted into an initially empty sorted linked list. 5 was inserted first, with its next pointer pointing to NULL. 2 was inserted after 5, with its next pointer pointing to 5. 7 was inserted after 2, with its next pointer pointing to 5. 6 was inserted after 7, with its next pointer pointing to 5. Finally, 5 was removed from the list, with 2's next pointer now pointing directly to 7.
1- By hand insert the following 4 numbers (5- 2- 7- 6) into an origina.docx
1. 1. By hand insert the following 4 numbers (5, 2, 7, 6) into an originally empty Sorted Linked
List. Indicate with each insertion what new connections are being made as well as what ones are
being broken. Indicate all connections with both arrow pointers and address values. Finally
remove the number 5 from the list.
2. Verify the above by implementing a Sorted Linked List in C.
Solution
//Program
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct SList
{
int data;
struct SList * next;
} L;
L * insert (int element, L * start) {
L * temp = (L *) malloc(sizeof(*start));
temp->data = element ;
temp->next = NULL ;
if (start == NULL) {
start = temp ;
}
L * t = start, * prev = NULL ;
while (t!=NULL) {
if (t->data < element) {
prev = t ;
t = t->next ;
2. }
}
prev->next=temp;
temp->next=t;
printf(" Element %d inserted",element);
return start ;
}
L * del (int val, L *list){
L * prev = NULL, * start = list ;
while (list != NULL) {
if (list->data == val) {
if ( prev != NULL ) prev->next = list->next ;
else start = list->next ;
free(list) ;
break ;
}
else {
prev = list ;
list = list->next ;
}
}
printf(" Element %d is removed", val );
return start ;
}
void print (L *list) {
if (list == NULL) {
printf("List is empty. ") ;
return ;
}
while(list != NULL) {
printf("%d ", list->data) ;
list = list->next;
}
printf(" ") ;
}
int main ()
{
L * head = NULL ;
head=insert(5,head);