Last active
September 7, 2022 13:20
-
-
Save imranhsayed/d63c39fe8422d04e820663157e58fb7b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Online C compiler to run C program online | |
#include <stdio.h> | |
#include <stdlib.h> | |
struct Node { | |
int data; // Data for the node. | |
struct Node *nextPtr; // Stores address of the next note. | |
}*firstNode; | |
// Function to create the list | |
void createNodeList( int noOfNodes ); | |
void displayList(); | |
int main() { | |
int noOfNodes; | |
printf("\n\n Linked List : To create and display Singly Linked List :\n"); | |
printf( "Enter the no of nodes: " ); | |
scanf( "%d", &noOfNodes ); | |
createNodeList( noOfNodes ); | |
printf("\n Data entered in the list : \n"); | |
displayList(); | |
return 0; | |
} | |
// Function to create the list | |
void createNodeList( int noOfNodes ) { | |
struct Node *fnNode, *temp; | |
int data, i; | |
firstNode = ( struct Node * )malloc( sizeof( struct Node ) ); | |
// If firstNode is NULL we cannot no memory allocation. | |
if(firstNode == NULL) { | |
printf(" Memory can not be allocated."); | |
} else { | |
// Take the data for the node. | |
printf(" Input data for node 1 : "); | |
scanf("%d", &data); | |
firstNode->data = data; | |
firstNode->nextPtr = NULL; // links the address field to NULL | |
temp = firstNode; | |
// Creating noOfNodes nodes and adding to linked list | |
for( i=2; i<=noOfNodes; i++) { | |
fnNode = (struct Node *)malloc(sizeof(struct Node)); | |
if(fnNode == NULL) { | |
printf(" Memory can not be allocated."); | |
break; | |
} | |
printf(" Input data for node %d : ", i); | |
scanf(" %d", &data); | |
// links the data field of fnNode with data | |
fnNode->data = data; | |
// links the address field of fnNode with NULL | |
fnNode->nextPtr = NULL; | |
temp->nextPtr = fnNode; // links previous node i.e. tmp to the fnNode | |
temp = temp->nextPtr; | |
} | |
} | |
} | |
void displayList() { | |
struct Node *temp; | |
if (firstNode == NULL) { | |
printf(" List is empty."); | |
} else { | |
temp = firstNode; | |
while (temp != NULL) { | |
printf( "Data = %d\n", temp->data ); | |
temp = temp->nextPtr; | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment