append() length() display() in Single linked list

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

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

void append();
int length();
void display();

int main()
{
	int ch, len;
	while(1)
	{
		printf("1.append \n");
		printf("2.length \n");
		printf("3.display \n");
		printf("4.quit \n");
		
		printf("Enter your choice : ");
		scanf("%d", &ch);
		
		switch(ch)
		{
			case 1	:	append();
						break;
						
			case 2 	:	len = length();
						printf("Length is : %d \n", len);
						break;
			
			case 3	:		display();
						break;
			
			case 4	:	exit(1);
			default	:	printf("Invalid choice \n");
		}
	}
	return 0;
}
void append()
{
	struct Node *new;
	new = (struct Node*)malloc(sizeof(struct Node));
		
	printf("\nEnter node data : ");
	scanf("%d", &new->data);
	new->link = NULL;
		
	if(root==NULL)
	{
		root = new;
	}
	else
	{
		struct Node *last = root;
		while(last->link != NULL)
		{
			last = last->link;
		}
		last->link = new;
	}
}

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

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

Add Comment

Courses Enquiry Form