ALGORITHM FOR SINGLY LINKED LIST OPERATIONS
1. 1. Include header files
#include <stdio.h>
#include <stdlib.h>
2. 2. Define the node structure
Define a structure Node with two members:
- int data;
- struct Node* next;
3. 3. Function: createNode(int value)
Allocate memory using malloc()
Assign value to data field
Set next to NULL
Return pointer to the new node
4. 4. Function: insertAtBeginning(Node** head, int value)
Create a new node
Point new node's next to current head
Update head to the new node
5. 5. Function: insertAtEnd(Node** head, int value)
Create a new node
If list is empty, head = new node
Else, traverse to the end and append new node
6. 6. Function: deleteAtBeginning(Node** head)
If list is empty, return
Update head to next node
Free the removed node
7. 7. Function: deleteAtEnd(Node** head)
If list is empty, return
If only one node, free it and set head to NULL
Else, traverse to second-last node, free last, and update pointer
8. 8. Function: printList(Node* head)
Traverse from head to end, printing each node's data
9. 9. Inside main() function
Declare Node* head = NULL;
Ask user for number of nodes n
Use loop to:
- Take value input
- Call insertAtEnd() for each value
Print the list
10. 10. Insert at Beginning
Ask user for a value
Call insertAtBeginning()
Print the list
11. 11. Insert at End
Ask user for a value
Call insertAtEnd()
Print the list
12. 12. Delete from Beginning
Call deleteAtBeginning()
Print the list
13. 13. Delete from End
Call deleteAtEnd()
Print the list