Answer:
#include <stdio.h> // header file
#include <stdlib.h>
struct node{ //define structure "node"
int data;
struct node* next; // object
};
struct node* add(struct node* head, int num);
struct node* delete(struct node* head, int num);
void print(struct node* head);
int size(struct node* head);
int main(int argc, char* argv[]){
FILE *fp = NULL;
struct node* head = NULL;
int num;
char command;
if(argc != 2){
printf("Please provide input filename as a command line argument\n");
return 1;
}
fp = fopen(argv[1], "r");
if(fp == NULL){
printf("error\n");
return 1;
}
fscanf(fp, "%c %d", &command, &num);
while(!feof(fp)){
if(command == 'i')
head = add(head, num);
else if(command == 'd')
head = delete(head, num);
fscanf(fp, "%c %d", &command, &num);
}
fclose(fp);
printf("%d\n",size(head));
print(head);
}
struct node* add(struct node* head, int num){
struct node* prev = NULL;
struct node* curr = head;
struct node* n = (struct node*) malloc(sizeof(struct node));
n->data = num;
n->next = NULL;
while(curr != NULL){
if(num < curr->data) //found a place to insert
break;
else if(num == curr->data) //duplicate
return head;
prev = curr;
curr = curr->next;
}
n->next = curr;
if(prev != NULL)
prev->next = n;
else
head = n;
return head;
}
struct node* delete(struct node* head, int num){
struct node* prev = NULL;
struct node* curr = head;
while(curr != NULL){
if(num < curr->data)
return head;
else if(num == curr->data)
break;
prev = curr;
curr = curr->next;
}
if(curr == NULL) //did not find
return head;
if(prev == NULL) //remove 1st node
head = curr->next;
else
prev->next = curr->next;
free(curr);
return head;
}
void print(struct node* head)
{
struct node* curr = head;
if(head != NULL){
printf("%d", curr->data);
curr = curr->next;
while(curr != NULL){
printf("\t%d", curr->data);
curr = curr->next;
}
}
printf("\n");
}
int size(struct node* head){
struct node* curr = head;
int count = 0;
while(curr != NULL){
count++;
curr = curr->next;
}
return count;
}
Output:
Provide input filename as a command-line argument
Test2 sg$ ./.s.out in.txt
2 5 8
1 2 3 5 10
Test2 sg$
Explanation:
we create a link list of integer in sorted order then if we input as 2 5 8, then 1 insert at the starting of the list and 3 in middle of 2 and 5 and 10 is inserted at the last.