Linked list example:Singly linked list with three methods
In this c code I've just write the code for a singly linked list. Here, I have used three methods. Which are
- push or insert data in the linked list in line no - 10
- print or display the data in the linked list in line no - 24
- Get count the total data in the linked list in line no - 41
For more on linked list, you can see my previous large lecture on linked list
See Linked List Details
- #include<stdio.h>
- #include<stdlib.h>
- struct Node
- {
- int data;
- struct Node *next;
- };
- typedef struct Node node;
-
- void pushData(node *list, int data)
- {
-
- while(list->next != NULL)
- {
- list = list -> next;
- }
-
- list->next = (struct node*)malloc(sizeof(struct node*));
- list = list->next;
- list->data = data;
- list->next = NULL;
- printf("Data inserted successfully..\n");
- }
- void printData(node *list)
- {
- printf("%d ", list ->data);
- while(list ->next != NULL){
-
- list = list ->next;
- printf("%d ",list->data);
-
- }
-
- {
-
- }
- printf("%d ",list->data);
- printData(list->next); */
- }
-
- int getCount(node *list){
- int count = 0;
- while(list -> next != NULL){
- count++;
- list = list->next;
- }
- return count;
- }
-
- int main( ){
-
- node *head,*temp;
- head = (struct node*)malloc(sizeof(struct node*));
-
- temp = head;
- temp -> next = NULL;
-
-
- int choose, value;
- printf("\n\nLinkedList");
-
- printf("\n\t\tEnter 1 to push data in the linked list : \n\t\tEnter 2 to see the linked list : \n\t\tEnter 3 to know the size of linked list : \n\t\tEnter 0 to exit\n---------------------------------------------\n");
- while(1){
-
- printf("Enter your Choose : ");
- scanf("%d", &choose);
- switch(choose){
- case 1:
- printf("Enter a value in the linked list : ");
- scanf("%d", &value);
- pushData(head, value);
- break;
- case 2:
-
- if(temp ->next == NULL){
- printf("Sorry No entry here ..");
- }else{
- printf("Total element in the linked list : ");
- printData(temp -> next);
- printf("\n");
- }
- break;
- case 3:
- printf("Total size of Linked list is : ");
- printf(" %d\n", getCount(temp->next) + 1);
- break;
- case 0:
- printf("Program exits\n");
- return 0;
- break;
- default:
- printf("Not match to any chosen value .\tPlease enter a correct chosen value.\n");
- }
- }
-
- }
Suggestion:Don't try to direct copy paste please. This habit will damage your coding power. Coding is an energy, is a habit, is a funny....So, try to solve your coding problem by yourself.
For more on linked list, you can see my
previous large lecture on linked list.
See Linked List Details
No comments:
Post a Comment