0

I have tried to create and display singly linked linked list using separate functions. the elements would be entered by the user. my program is taking input but not displaying those elements. any help would be greatly appreciated


#include <stdio.h>
#include <stdlib.h>
struct node{
    int data; 
    struct node *next; 
};
void create(int n, struct node *newnode, struct node *prev, struct node *head){
    for(int i=0; i<n; i++){
        printf("Enter the data for node %d: ", i+1);
        scanf("%d", &newnode-> data);
        if(head==NULL){
            head = newnode;
            head-> next = NULL;
            prev = head;
        }
        else{
            prev->next= newnode;
            newnode->next= NULL;
            prev=newnode;
        }
    }
}
void display(int n, struct node *temp){
         printf("%d ", temp->data);
         temp=temp->next;
    
}
int main()
{
    struct node *newnode, *prev, *head, *temp;
    newnode = (struct node*)malloc(sizeof(struct node *));
    head=NULL;
    int n, choice;
    printf("Number of elements in your linked list: ");
    scanf("%d", &n);
    create(n, newnode, prev, head);
    printf("\n1.Display");
    printf("Enter the operation you would like to perform: ");
    scanf("%d",&choice);
    if(choice==1){
        temp=head;
        display(n, temp);
        
    }
    return 0;}

Quimby
  • 17,735
  • 4
  • 35
  • 55
vaibhp
  • 1
  • 1
  • 1
    What have you found while stepping through the code with a debugger? – Quimby Sep 30 '22 at 12:00
  • 2
    Does this answer your question? [How do I modify a pointer that has been passed into a function in C?](https://stackoverflow.com/questions/766893/how-do-i-modify-a-pointer-that-has-been-passed-into-a-function-in-c) – UnholySheep Sep 30 '22 at 12:01
  • newnode = (struct node*)malloc(sizeof(struct node *)); will malloc the size of a pointer. You should be using malloc(sizeof(struct node)) instead. – jmq Sep 30 '22 at 21:01

0 Answers0