Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<stdlib.h>
- #include<stdbool.h>
- struct Node{
- int info;
- struct Node *next;
- };
- typedef struct Node NodeType;
- // Two glboal variables to store address of first and last nodes.
- NodeType *first =NULL , *last = NULL;
- NodeType* getNode(){
- NodeType *ptr;
- ptr = (NodeType *) malloc(sizeof(NodeType));
- return ptr;
- }
- void createEmptyList(NodeType *first){
- first =NULL;
- printf("\nList is emptied.\n");
- }
- void insertatBegin(int item){
- NodeType *newnode;
- NodeType *temp;
- temp = first; //hold the address of the first node of list(which is already present)
- newnode = getNode(); //creates the new node
- newnode ->info = item; //info section of new node
- //filling next(address) section of new node
- if(first ==NULL){ //if the linked list is empty i.e. first address is null
- newnode ->next =NULL;
- first = last = newnode; //there is only one node so first and last is same node
- }
- else{ //if not empty
- newnode ->next = temp;
- first = newnode;
- }
- }
- void insertatEnd(int item){
- NodeType *newnode;
- newnode =getNode();
- newnode -> info =item;
- newnode -> next =NULL;
- if (first == NULL) {
- first = newnode;
- last = newnode;
- }
- else
- {
- last -> next = newnode;
- last = newnode;
- }
- }
- void displayElements(){
- NodeType *temp;
- if (first == NULL) {
- printf("\n Linked list is empty.\n");
- exit(1);
- }
- else
- {
- while(temp != NULL){
- printf("%d\t",temp->info);
- temp = temp ->next;
- }
- }
- }
- int main(int argc, char const *argv[])
- {
- int item,ch;
- while(1){
- printf("\n---------------------------------\n");
- printf("\nOperations on singly linked list\n");
- printf("\n---------------------------------\n");
- printf("\n0.Make List Empty");
- printf("\n1.Insert node at first");
- printf("\n2.Insert node at last");
- printf("\n3.Insert node at position");
- printf("\n4.Delete first Node");
- printf("\n5.Delete last node");
- printf("\n6.Delete Node from any Position");
- printf("\n7.Sum of all data(info) of nodes");
- printf("\n8.Count no. of nodes");
- printf("\n9.Search Element in the linked list");
- printf("\n10.Display List from Beginning to end");
- printf("\n11.Exit\n");
- printf("\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
- printf("Enter your choice : ");
- scanf("%d",&ch);
- switch (ch)
- {
- case 0:
- createEmptyList(first);
- break;
- case 1:
- printf("Enter the item to be inserted : ");
- scanf("%d",&item);
- insertatBegin(item);
- break;
- case 2:
- printf("Enter the item to be inserted : ");
- scanf("%d",&item);
- insertatEnd(item);
- break;
- case 3:
- break;
- case 4:
- break;
- case 5:
- break;
- case 6:
- break;
- case 7:
- break;
- case 8:
- break;
- case 9:
- break;
- case 10:
- displayElements();
- break;
- case 11:
- exit(1);
- default:
- break;
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement