Singly Linked List
Singly Linked List
h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
void create()
{
newnode = (struct node *)malloc(sizeof(struct node));
printf("Enter data: ");
scanf("%d", &newnode->data);
newnode->next = NULL;
if (head == NULL)
{
head = temp = newnode;
}
else
{
temp->next = newnode;
temp = newnode;
}
count++;
printf("\nNode count: %d", count);
}
void display()
{
temp = head;
printf("\nLinked List: ");
while (temp != NULL)
{
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
void insert()
{
newnode = (struct node *)malloc(sizeof(struct node));
int ch;
printf("Enter data: ");
scanf("%d", &newnode->data);
newnode->next = NULL;
if (ch == 1)
{
newnode->next = head;
head = newnode;
count++;
}
else if (ch == 2)
{
if (head == NULL)
{
head = newnode;
} else
{
temp = head;
while (temp->next != NULL)
{
temp = temp->next;
}
temp->next = newnode;
}
count++;
}
else if (ch == 3)
{
int pos, i = 1;
printf("Enter position: ");
scanf("%d", &pos);
if (pos == 1)
{
newnode->next = head;
head = newnode;
}
else
{
temp = head;
while(i<pos-1)
{
temp = temp->next;
i++;
}
newnode->next = temp->next;
temp->next = newnode;
}
count++;
}
printf("\nNode count: %d", count);
}
int main()
{
int ch;
do {
printf("\nMENU\n1. Create Node\t2. Display List\t3. Insert Node\t4.
Exit\n");
printf("Enter your choice: ");
scanf("%d", &ch);
switch (ch)
{
case 1:
create();
break;
case 2:
display();
break;
case 3:
insert();
break;
case 4:
break;
default:
printf("Invalid choice\n");
}
} while (ch != 4);
return 0;
}
Output:
MENU
1. Create Node 2. Display List 3. Insert Node 4. Exit
Enter your choice: 1
Enter data: 10
Node count: 1
MENU
1. Create Node 2. Display List 3. Insert Node 4. Exit
Enter your choice: 1
Enter data: 20
Node count: 2
MENU
1. Create Node 2. Display List 3. Insert Node 4. Exit
Enter your choice: 1
Enter data: 30
Node count: 3
MENU
1. Create Node 2. Display List 3. Insert Node 4. Exit
Enter your choice: 3
Enter data: 40
MENU
1. Insert at beginning
2. Insert at end
3. Insert at a specific position
Enter your choice: 1
Node count: 4
MENU
1. Create Node 2. Display List 3. Insert Node 4. Exit
Enter your choice: 2
MENU
1. Create Node 2. Display List 3. Insert Node 4. Exit
Enter your choice: 3
Enter data: 100
MENU
1. Insert at beginning
2. Insert at end
3. Insert at a specific position
Enter your choice: 2
Node count: 5
MENU
1. Create Node 2. Display List 3. Insert Node 4. Exit
Enter your choice: 2
MENU
1. Create Node 2. Display List 3. Insert Node 4. Exit
Enter your choice: 3
Enter data: 900
MENU
1. Insert at beginning
2. Insert at end
3. Insert at a specific position
Enter your choice: 3
Enter position: 3
Node count: 6
MENU
1. Create Node 2. Display List 3. Insert Node 4. Exit
Enter your choice: 2
Linked List: 40 -> 10 -> 900 -> 20 -> 30 -> 100 -> NULL
MENU
1. Create Node 2. Display List 3. Insert Node 4. Exit
Enter your choice: