Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- struct node{
- int data;
- struct node* next;
- }*headA = NULL;
- void display(struct node* help){
- if(!help) printf(" Empty!");
- while(help){
- printf(" %d ", help->data);
- help = help->next;
- }
- }
- struct node* insert(int value, struct node*help){
- struct node *newNode = (struct node*) malloc(sizeof(newNode));
- newNode->data = value; newNode->next = NULL;
- if(help) newNode->next = help;
- help = newNode;
- display(help);
- return help;
- }
- struct node* input(struct node *head){
- int n;
- while(1){
- printf("\nInput(-1 to stop): ");
- scanf("%d",&n);
- if(n!=-1) head = insert(n, head);
- else return head;
- }
- }
- void copy(struct node* help){
- struct node *headB = NULL, *last = NULL;
- while(help){
- struct node *newNode = (struct node*) malloc(sizeof(struct node));
- newNode->data = help->data; newNode->next = NULL;
- if(!headB){
- headB = newNode;
- last = newNode;
- } else{
- last->next = newNode;
- last = last->next;
- }
- help = help->next;
- }
- help = last = NULL;
- free(help); free(last);
- printf("\nThe copied linked list is:");
- display(headB); free(headB);
- }
- void concatenate(struct node *help){
- struct node *headB = NULL;
- printf("\nEnter elements for the second Linked List\n");
- headB = input(headB);
- if(!help) headA = headB;
- while(help->next) help = help->next;
- help->next = headB;
- printf("\nTwo linked lists have been concatenated:");
- display(headA);
- headB = NULL; free(headB);
- }
- void split(struct node *help, int index){
- for(int i = 0; i < index; i++) help = help->next;
- struct node *headB = help->next;
- help->next = NULL;
- printf("\nThe first linked list:"); display(headA);
- printf("\nThe second linked list:"); display(headB); free(headB);
- }
- void reverse(struct node* help){
- struct node *forward = headA, *back = NULL;
- while (forward){
- help = forward;
- forward = help->next;
- help->next = back;
- back = help;
- }
- headA = back;
- back = forward = help = NULL;
- free(back); free(forward); free(help);
- printf("\nThe linked list has been reversed:");
- display(headA);
- }
- int count(struct node* help){
- int count = 0;
- while(help){
- count++;
- help = help->next;
- }
- return count;
- }
- int main(){
- int n;
- printf("\nEnter elements for first Linked List.\n");
- headA = input(headA);
- while(1){
- printf("\n1.Copy 2.Concatenate 3.Split 4.Reverse 5.Count 6.Exit: ");
- scanf("%d",&n);
- switch(n){
- case 1: copy(headA); break;
- case 2: concatenate(headA); break;
- case 3: split(headA,count(headA)/2-1); break;
- case 4: reverse(headA); break;
- case 5: printf("\nThe number of nodes are %d.", count(headA)); break;
- case 6: return 0;
- default: printf("\nEnter a number between 1 and 6.");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement