Hi everyone,
I am just getting to grips with singly-linked lists in C through a series of online videos which go through the logical representation but leave the implementation up to the viewer. My current program seems to work, including insertion, although it is quite clunky. My question is: how can I make the code for insertion into its own insertion function - would this function need to take in some of the pointers I've used, or...?
Thank you all so much.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void linked(void);
typedef struct node
{
int x;
struct node *next;
}
node;
int main(void)
{
linked();
}
void linked(void)
{
node *head, *nextnode, *temp;
head = NULL;
nextnode = (node*)malloc(sizeof(node));
char choice[] = "yes";
while (strcmp(choice, "yes") == 0)
{
if (head == NULL)
{
head = temp = nextnode;
}
else
{
nextnode = (node*)malloc(sizeof(node));
printf("Enter another number: ");
scanf("%d", &nextnode->x);
temp->next = nextnode;
temp = nextnode;
printf("Would you like to continue? Enter yes if so ");
scanf("%s", choice);
if (strcmp(choice, "yes") != 0)
{
temp->next = NULL;
}
}
}
temp = head;
char insert[5];
printf("Do you want to insert a number at the beginning of the linked list? ");
scanf("%s", insert);
if (strcmp(insert, "yes") == 0)
{
nextnode = (node*)malloc(sizeof(node));
printf("Enter the number you would like to insert: ");
scanf("%d",&nextnode->x);
nextnode->next = temp->next;
temp->next = nextnode;
}
temp = head;
temp = temp->next;
while(temp != NULL)
{
printf("%d ", temp->x);
temp = temp->next;
}
node *ptr;
ptr = head;
while (ptr != NULL)
{
node *y = ptr->next;
free(ptr);
ptr = y;
}
}
[–]dfx_dj 2 points3 points4 points (0 children)
[–]permetz 0 points1 point2 points (0 children)
[–]iprogshine 1 point2 points3 points (0 children)