Click here to Skip to main content
15,891,607 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C#
<pre>
#include<stdio.h>
#include<stdlib.h>

struct node {
    int data;
    struct node *next;
};

struct node *createNode(){
    struct node *ptr,*head;
    ptr= (struct node *)malloc(sizeof(struct node));
    ptr->next = NULL;
}

struct node *input(){
    int num;
    struct node *p,*head,*temp;
    for(int i=0;i<5;i++){
		scanf("%d",&num);
        temp=createNode();
        temp->data=num;
    
    if(head == NULL){
        p=head=temp;
    }
    
    else{
        p=temp;
     }
    }
    return head;
}

struct node *insertNode(int value){
    struct node *p,*head,*neww;
    neww = createNode();
    neww ->data=value;
    
    if(head==NULL){
        head = neww;
    }
    else{
        while(p!=NULL){
            p->next=p;
            p = neww;
        }
    }
}

void display(struct node * head){
  struct node * ptr=head;
  while(ptr!=NULL){
    printf("%d ",ptr->data);
    ptr=ptr->next;
  }
}

void main(){
     struct node * head = input();
     insertNode(3);
     display(head);
}


What I have tried:

I have written this code ,what is wrong with this?
Posted
Updated 23-Jun-17 1:28am

1 solution

There is a lot wrong with it.

You can find multiple tutorials and examples in the net about linked lists. I suggest to have a look at some first.

The main problem with your code is that you have to understand that the head variable is required by nearly all operations and does not change once it has been initialised. So it has to be a global variable or a local instance that must be passed to each function once it has been created. You have done this for your display() function but not for the others.

Your code is also not handling insertion of new nodes properly. There you have to set the next member of the previous node to your newly created node. When performing an insert (not an append), you must also set the next member of the new node to the one that was set in the previous one. So you have to pass either the previous node to your insert function or the head. When passing the head you can insert on top (just behind head) or step through the list to locate the last node and append.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900