Menu Close

Create Display Linked List

Create – Display Linked List:

  • In this program, we defined 3 functions.
  • Create function is used to create the list of nodes using iterator.
  • Length function returns the length of list
  • Display function displays all nodes data.
#include<stdio.h>
#include<stdlib.h>

struct Node
{
	int data;
	struct Node* link;	
};
struct Node* root=NULL;

void create();
int length();
void display();

int main()
{
	int ch, len;
	
	printf("Create list with some data initially : \n");
	create();
	
	while(1)
	{
		printf("\n1.Display \n");
		printf("2.Length \n");
		printf("3.Quit \n");
		
		printf("Enter your choice : ");
		scanf("%d", &ch);
		
		switch(ch)
		{
			case 1 :	display();
						break;
			
			case 2 :	len = length();
						printf("Node count is : %d\n", len);
						break;
			
			case 3 :	exit(1);
			
			default :	printf("Invalid choice...\n");
		}
	}
	return 0;	
};

void create()
{
	struct Node *temp, *p;
	while(1)
	{
		temp = (struct Node*)malloc(sizeof(struct Node));
		printf("Enter node data : ");
		scanf("%d" , &temp->data);
		
		if(root==NULL)
		{
			root = temp;
			p = temp;
		}
		else
		{
			p->link = temp;
			p = temp;
		}
		
		printf("Do you want to continue(y/n) : ");
		if(getche()=='n')
		{
			p->link = NULL;
			break;
		}
	}
}

void display()
{
	struct Node* temp;
	if(root == NULL)
	{
		printf("List is Empty \n");
	}
	else
	{
		temp=root;
		while(temp)
		{
			printf("%d \n", temp->data);
			temp=temp->link;
		}
	}
}

int length()
{
	struct Node* temp=root;	
	int count=0;
	while(temp)
	{
		++count ;
		temp = temp->link ;
	}
	return count ;
}