Ok, I've managed to solve the insertion and the print function which works now. So I wanted to add more functions to modify the list, specifically delete and searching. I'm having trouble deleting 1 of the remaining nodes.
For example, if I input values of say 5, 2, 9, 6. The program will print them in order 2, 5, 6, 9. When I delete it only manages to delete the 5, 6, 9 and not the 2. The first number of the list never gets deleted
Heres what I have so far:
Code:
#include <stdio.h>
#include <stdlib.h>
#define FALSE 0
#define TRUE 1
typedef struct NODE {
struct NODE *link;
int value;
} Node;
// Function Prototypes
int sll_insert(register Node **linkp);
int view_list(register Node *linkp);
int delete_whole(Node *linkp);
int search_list(register Node *linkp, int value);
int delete_specific(register Node *linkp, int value);
// Main Function
int main(int argc, char **argv)
{
int input;
int c;
Node *root = NULL;
do
{
printf("1. Add value\n");
printf("2. View list\n");
printf("3. Delete whole list\n");
printf("4. Searching\n");
printf("5. Delete specific node(s)\n");
printf("6. Exit\n\n");
printf("Your current option is: ");
scanf("%d",&input);
switch(input){
case 1:
sll_insert(&root);
break;
case 2:
view_list(root);
break;
case 3:
delete_whole(root);
break;
case 6:
printf("Now exiting!\n");
exit(0);
default:
printf("Invalid key.. Now exiting!\n");
exit(0);
break;
}
} while (1);
return 0;
}
int sll_insert(register Node **linkp)
{
register Node *current;
register Node *new;
int input_value = 0;
printf("Input a number: ");
scanf("%d",&input_value);
// Look for the right place until we reach a node whose value is greater
// than or equal to the input_value variable
while((current = *linkp) != NULL && current->value < input_value)
linkp = ¤t->link;
// Allocate a new node and store the new value into it
new = (Node *)malloc(sizeof(Node));
if (new == NULL)
return FALSE;
new->value = input_value;
// Insert the new node into the list and return TRUE
new->link = current;
*linkp = new;
return TRUE;
}
int view_list(register Node *linkp)
{
register Node *current;
if (linkp == NULL) {
printf("There is nothing in the list!\n");
return 1;
}
current = linkp;
while (current->link != NULL)
{
printf("%d ",current->value);
current = current->link;
}
// Used to print out the last one
printf("%d ",current->value);
printf("\n");
}
int delete_whole(Node *linkp)
{
Node *current;
if (linkp == NULL) {
printf("There is nothing to delete!\n");
return 1;
}
// Start deleting
current = linkp;
while(current != NULL)
{
free(current);
current = current->link;
}
// Delete remaining
free(current);
printf("\n\nThe list has been fully deleted!\n\n");
}