data structures - Basic Linked List operations in C -
i creating program perform basic linked list operations. right have wrote code inserting node @ front. ran program see working or not program terminating after accepting input node, prints message after switch. doesn't pause accepting input continuing operations (just before end of main())
here code :
#include <stdio.h> #include <stdlib.h> struct linkedlist { int num; struct linkedlist *next; }; struct linkedlist *head = null; void display(); void insertbeginning() { struct linkedlist *obj; int no; obj = (struct linkedlist *)malloc(sizeof(struct linkedlist)); if(obj == null) { printf("\n overflow "); } else { printf("\n enter number = "); scanf("%d", &no); obj->num = no; if(head == null) { head = obj; obj->next = null; } else { obj->next = head; head = obj; } } } void display () { struct linkedlist *head2 = head; while(head2 != null) { printf("%d ->",head2->num); head2=head->next; } printf("null \n"); } int main() { int choice; char wish; printf("\n 1. insert @ beginning"); printf("\n 2. insert @ end"); printf("\n 3. insert in between"); printf("\n 4. delete front"); printf("\n 5. delete end"); printf("\n 6. delete in between"); printf("\n 7. reverse"); printf("\n 8. sort ascending"); printf("\n 9. sort descending"); printf("\n 10.swap alternate elements"); printf("\n 11.display\n\n"); { printf("\n enter option = "); scanf("%d", &choice); switch(choice) { case 1: insertbeginning(); break; case 2: // insertend(); break; case 3: // insertinbetween(); break; case 4: // deletefront(); break; case 5: // deleteend(); break; case 6: // deleteinbetween(); break; case 7: // reverse(); break; case 8: // sortasc(); break; case 9: // sortdesc(); break; case 10: // swap(); break; case 11: display(); break; default: printf("\n wrong choice "); } printf("\n wish continue (y/n) = "); scanf ("%c",&wish); }while(wish == 'y' || wish =='y'); return 0; }
in case, have change
scanf ("%c",&wish);
to
scanf (" %c",&wish);
because, if don't include leading white-space before format specifier, consider remaining \n
(newline) got generated , stored input buffer pressing enter key after first input. so, second scanf()
won't wait user input.
Comments
Post a Comment