In this post, we'll walk over the Singly Linked List and its implementation using C language. In a singly linked list, each node in the list stores two things - contents of node and the pointer to next node. It is called singly linked list because every node has only pointer i.e. pointer to next node. Last node will typically point to NULL indicating the end of list. Typically, we will have a head which will be used to intialize the empty list and will point to NULL.
#include<stdio.h> #include<stdlib.h> typedef struct node { int key; struct node *nextNode; } LinkNode; LinkNode *addNode(LinkNode *nodePtr, int value) { LinkNode *newNode = (LinkNode *) malloc(sizeof(LinkNode)); if (newNode == NULL) { fprintf(stderr, "Error creating new node, terminating program \n "); exit(1); } newNode->key = value; newNode->nextNode = nodePtr; return newNode; } LinkNode *deleteNode(LinkNode *nodePtr, int value) { LinkNode *head = nodePtr; LinkNode *prevNode = nodePtr; while (nodePtr != NULL) { if (nodePtr->key == value) { // When we are dealing with the first node if (prevNode == nodePtr) { if (nodePtr->nextNode == NULL) { free(nodePtr); return NULL; } head = nodePtr->nextNode; free(nodePtr); return head; } prevNode->nextNode = nodePtr->nextNode; free(nodePtr); return head; } prevNode = nodePtr; nodePtr = nodePtr->nextNode; } return head; } void printList(LinkNode *nodePtr) { if (nodePtr == NULL) printf("No elements in the list\n"); while (nodePtr != NULL) { printf("Value : %d\n", nodePtr->key); nodePtr = nodePtr->nextNode; } } int main() { LinkNode *head; head = NULL; char cmd; int nargs, nvalue; while (1) { do { printf("Enter command : "); nargs = scanf(" %c", &cmd); } while (nargs != 1); switch (cmd) { case 'a': case 'A': do { printf("Enter the value for the node to be added : "); nargs = scanf("%d", &nvalue); } while (nargs != 1); head = addNode(head, nvalue); break; case 'p': case 'P': printList(head); break; case 'd': case 'D': do { printf("Enter the value for the node to be deleted : "); nargs = scanf("%d", &nvalue); } while (nargs != 1); head = deleteNode(head, nvalue); break; case 'q': case 'Q': return 0; default: printf("Invalid Command : %c \n", cmd); } } return 0; }
Comments
Post a Comment