Linked list using C
August 17, 2019 Leave a comment
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> typedef struct LLNode { int data; struct LLNode* nextNode; }Node;//Alias name void AddNewNodeAtEnd(Node* head,int data) { Node *newNode = NULL; newNode = malloc(sizeof(Node)); if(newNode == NULL) { printf("Error while creating node!!"); } else { //printf("Created node!!"); newNode->data = data; newNode->nextNode = NULL; Node * t_head = head; //add this node to the end of the list while(t_head->nextNode!= NULL) { t_head = t_head->nextNode; } //add the node t_head->nextNode = newNode; } } //This function replaces the existing Node * head reference Node* AddNewNodeAtBegin(Node* head, int data) { Node* newNode = malloc(sizeof(Node)); newNode->data = data; newNode->nextNode = head; return newNode; } int PrintLinkedList(Node *head) { printf("\nPrinting the LinkedList : \n"); Node* t_head = head; if(head == NULL) { printf("List is empty!"); return 0; } while(t_head != NULL) { printf("%d \n",t_head->data); t_head = t_head->nextNode; } printf("\n ----------------------------------- \n"); return 0; } //This one searches and deletes a node void DeleteBeginNode(Node** head) { if((*head)->nextNode == NULL) (*head)= NULL; else { (*head) = (*head)->nextNode; } } void DeleteLastNode(Node** head) { //when list size is 1 if((*head)->nextNode == NULL) (*head)= NULL; else { Node * temp = *head; //when list size is 2 or more while(temp->nextNode->nextNode != NULL) { temp = temp->nextNode; } temp->nextNode = NULL; } } int main(void) { //eclipse specifics setvbuf(stdout, NULL, _IONBF, 0); setvbuf(stderr, NULL, _IONBF, 0); //Create Head Node Node * head = NULL; head = malloc(sizeof(Node)); printf("\nEnter data for HeadNode : "); scanf("%d",&head->data); head->nextNode = NULL; int count = 0; int data = 0; printf("Enter the number of nodes to add at end : "); scanf("%d",&count); for(int i=0; i<count; i++) { printf("Enter the data : "); scanf("%d",&data); AddNewNodeAtEnd(head, data); } //print the entire list PrintLinkedList(head); //Add new node at front printf("\n Adding a new node at beginning "); scanf("%d",&data); head = AddNewNodeAtBegin(head, data); //print the entire list PrintLinkedList(head); //Delete head node printf("\nPress any key to delete the head node"); scanf("%d",&data); DeleteBeginNode(&head); //print the entire list PrintLinkedList(head); //Delete tail node printf("\nPress any key to delete the tail node"); scanf("%d",&data); DeleteLastNode(&head); //print the entire list PrintLinkedList(head); //Delete tail node printf("\nPress any key to delete the tail node"); scanf("%d",&data); DeleteLastNode(&head); //print the entire list PrintLinkedList(head); printf("\n\n =========== END ============ "); return EXIT_SUCCESS; }