Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<stdlib.h>
- int ll_size = 0;
- struct Node{
- int value;
- struct Node *next;
- };
- typedef struct Node Node;
- struct Node *head = NULL;
- void Insertion(int pos , int ele){
- Node *temp = ( Node*) ( malloc(sizeof(Node) ) );
- if( ( pos>ll_size+1 || pos<1) || temp == NULL){
- printf("\nYou entered wrong position or memory is not allocated");
- return;
- }
- temp->value = ele;
- if(pos == 1){
- if(head == NULL){
- temp->next = temp;
- }else{
- Node *ptr = head;
- while(ptr->next != head){
- ptr = ptr->next;
- }
- ptr->next = temp;
- temp->next = head;
- }
- head = temp;
- }
- else{
- struct Node *ptr = head;
- pos-=2;
- while(pos--){
- ptr = ptr->next;
- }
- temp->next = ptr->next;
- ptr->next = temp;
- }
- ll_size++;
- }
- void Deletion(int pos){
- if(head == NULL || (pos>ll_size || pos<1) ){
- printf("\nlinked list is empty already or you have entered wrong position");
- return;
- }
- Node* dele = head;
- if(pos == 1){
- if(head->next == head){
- head = NULL;
- }else{
- Node *ptr = head;
- while(ptr->next != head){
- ptr = ptr->next;
- }
- ptr->next = head->next;
- head = head->next;
- }
- free(dele);
- }
- else{
- Node *ptr = head;
- pos-=2;
- while(pos--){
- ptr = ptr->next;
- }
- dele = ptr->next;
- ptr->next = ptr->next->next;
- free(dele);
- }
- ll_size--;
- }
- void Print(){
- Node *ptr = head;
- if(head != NULL){
- do{
- printf("%d ",ptr->value);
- ptr = ptr->next;
- }while(ptr != head);
- }
- printf("& there are %d nodes in link list\n",ll_size);
- }
- int main()
- {
- int choice,ele,pos,key;
- while(1){
- printf("1 for insertion, 2 for deletion & any to key just print the link list : ");
- scanf("%d",&choice);
- if(choice == 1){
- printf("Enter the position where you want to insert the element : ");
- scanf("%d",&pos);
- printf("Enter the element : ");
- scanf("%d",&ele);
- Insertion(pos,ele);
- }
- else if (choice == 2){
- printf("\nEnter the position want to delete ");
- scanf("%d",&pos);
- Deletion(pos);
- }
- else Print();
- printf("1 to repeat and any key to exit ");
- scanf("%d",&key);
- if(key != 1) break;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment