creating a linkedlist and display the data in it

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;

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

// head pointer holds the address of the starting node of the linked list
struct node *head;

int createLinkedList(){
    struct node *newnode,*temp;
    newnode = (struct node*)malloc(sizeof(struct node));
    printf("\nenter the data into the linked list:");
    scanf("%d", &newnode->data);
    newnode->next=NULL;
    if(head == NULL){
        head = newnode;
        return 1;
    }
    else{
        temp = head;
        while(temp->next!=NULL)
        {
            temp = temp->next;
        }
        temp->next=newnode;
        return 1;
    }
}
void display()
{
    struct node *temp;
    temp = head;
    if(head!=NULL){
        for(temp = head; temp!=NULL; temp = temp->next){
            printf("%d\n",temp->data);
        }
    }
    else{
        printf("The list is empty...");
    }

}
int main()
{
    int ch;
    head = NULL;
    do{
        printf("\n1.create linked list");
        printf("\n2.display linked list");
        printf("\n3.exit");
        printf("\n4.enter your choice:");
        scanf("%d", &ch);
        switch(ch)
        {
        case 1:
            createLinkedList();
            break;
        case 2:
            display();
            break;
        case 3:
            exit(1);
            break;
        default:
            printf("\nwrong entry please continue try...");

        }
    }while(ch!=3);
}
0

Leave a Reply

Your email address will not be published.