Display Singly Linked List -hrithikpc, Exercises of Computer Science

C program to create and display Singly Linked List -hrithikpc

Typology: Exercises

2017/2018

Uploaded on 10/06/2018

Hrithik-mojumdar
Hrithik-mojumdar 🇧🇩

4.4

(8)

2 documents

1 / 3

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
/**
* C program to create and display Singly Linked List
*/
#include <stdio.h>
#include <stdlib.h>
/* Structure of a node */
struct node {
int data; //Data part
struct node *next; //Address part
}*head;
/*
* Functions to create and display list
*/
void createList(int n);
void traverseList();
int main()
{
int n;
printf("Enter the total number of nodes: ");
scanf("%d", &n);
createList(n);
printf("\nData in the list \n");
traverseList();
return 0;
}
/*
* Create a list of n nodes
*/
void createList(int n)
{
struct node *newNode, *temp;
int data, i;
head = (struct node *)malloc(sizeof(struct node));
/*
* If unable to allocate memory for head node
*/
if(head == NULL)
{
printf("Unable to allocate memory.");
}
else
{
pf3

Partial preview of the text

Download Display Singly Linked List -hrithikpc and more Exercises Computer Science in PDF only on Docsity!

  • C program to create and display Singly Linked List */

#include <stdio.h> #include <stdlib.h>

/* Structure of a node */

struct node { int data; //Data part struct node next; //Address part }head;

  • Functions to create and display list */

void createList(int n); void traverseList();

int main() {

int n;

printf("Enter the total number of nodes: "); scanf("%d", &n);

createList(n);

printf("\nData in the list \n"); traverseList();

return 0; }

  • Create a list of n nodes */ void createList(int n) { struct node *newNode, *temp; int data, i;

head = (struct node *)malloc(sizeof(struct node));

  • If unable to allocate memory for head node */ if(head == NULL) { printf("Unable to allocate memory."); } else {
  • Reads data of node from the user */ printf("Enter the data of node 1: "); scanf("%d", &data);

head->data = data; //Links the data field with data head->next = NULL; //Links the address field to NULL

temp = head;

  • Creates n nodes and adds to linked list */ for(i=2; i<=n; i++) { newNode = (struct node *)malloc(sizeof(struct node));

/* If memory is not allocated for newNode */ if(newNode == NULL) { printf("Unable to allocate memory."); break; } else { printf("Enter the data of node %d: ", i); scanf("%d", &data);

newNode->data = data; //Links the data field of newNode with data newNode->next = NULL; //Links the address field of newNode with NULL

temp->next = newNode; //Links previous node i.e. temp to the newNode temp = temp->next; } } } }

  • Displays the entire list */ void traverseList() {

struct node *temp;

  • If the list is empty i.e. head = NULL */ if(head == NULL) { printf("List is empty."); }