Menu Close

Adding elements to linked list

append():

  • This function is used to add element at the end of list.
  • If no nodes in the list, it will become the first node in the list.
  • If the list has elements, then we need to traverse from first node to last node and add the new element at the end of list.

addFirst():

  • This function is used to add element at the beginning of list.
  • New node become the first node in the list.

Program code:

#include<stdio.h>
#include<stdlib.h>
struct Node
{
	int data;
	struct Node* link;	
};
struct Node* root=NULL;

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

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.Append \n");
		printf("4.Add First \n");
		printf("5.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 :	append();
					break;
			
			case 4 :	addFirst();
					break;
			
			case 5 :	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 ;
}

void append()
{
	struct Node *temp;
	temp = (struct Node*)malloc(sizeof(struct Node));
	printf("Enter node data : ");
	scanf("%d" , &temp->data);
	temp->link = NULL;
	if(root==NULL)
	{
	root = temp;
	}
	else
	{
		struct Node* p=root;
		while(p->link)
		{
			p=p->link;
		}
		p->link = temp;		
	}
}

void addFirst()
{
	struct Node *temp;
	temp = (struct Node*)malloc(sizeof(struct Node));
	printf("Enter node data : ");
	scanf("%d" , &temp->data);
	temp->link = root;
	root = temp;
}