Hackety Hacking Problem Compare and copy
Jump to navigation
Jump to search
Problem Statement
You are the coordinator of the class and you have been assigned the task of maintaining the test results of the students. You have to take marks alloted to the students as input and then compare it with the final list given to you by the teacher. Being intelligent, you try to speed up your task by making a program which can accept marks of the student and then compare it with the list given to by teacher.
You don't know the number of students in the class. Therefore you have a create a dynamic list.
HINT: Write a program to compare two linked list using recursion. And hence write a program to copy one linked list into another using recursion.
Sample Output
To be done.......
Curriculum Connections
To be done.......
Solution
#include<stdio.h> #include<conio.h> #include<stdlib.h> typedef struct node { int info; struct node* ptr; } node; node *sptr1=NULL, *sptr2=NULL; int menu() { int ch; printf("\nenter ur choice\n"); printf("1.add node\n2.compare lists\n3.traverse list\n4.copy link list\n5.exit\n"); scanf("%d",&ch); return ch; } node *addnode(node *sptr) { node *temp; temp=(node*) malloc (sizeof(node)); temp->ptr=NULL; temp->info=NULL; printf("enter the no."); scanf("%d",&temp->info); if(sptr==NULL) sptr=temp; else { temp->ptr=sptr; sptr=temp; } return sptr; } int compare(node *ptr1,node *ptr2) { if((ptr1->info==ptr2->info) && ptr1!=NULL && ptr2!=NULL) { ptr2=ptr2->ptr; ptr1=ptr1->ptr; compare(ptr1,ptr2); } if(ptr1==NULL && ptr2==NULL) { printf("the link lists r equal"); return (0); } else if(ptr1==NULL) { printf("linklist 1 is smaller and not equal"); return(0); } else if(ptr2==NULL) { printf("linklist 2 is smaller and not equal"); return 0;} else printf("the lists are not equal"); return 0; } int copy(node *ptr1,node *ptr2) { if(ptr1!=NULL && ptr2!=NULL) { ptr2->info=ptr1->info; ptr1=ptr1->ptr; ptr2=ptr2->ptr; copy(ptr1,ptr2); } return 0; } int traverse(node *sptr) { node *t; t=sptr; while(t->ptr) { printf("%d\t",t->info); t=t->ptr; } printf("%d",t->info); return 0; } int main() { int i; do { switch(menu()) { case 1: printf("enter the link list in which u wanna enter element\n"); printf("1.1st link lis\n2.2nd link list\n"); scanf("%d",&i); if(i==1) sptr1=addnode(sptr1); else if(i==2) sptr2=addnode(sptr2); else printf("enter correctly"); break; case 2: compare(sptr1,sptr2); break; case 3: printf("enter the list no. to be traversed\n"); scanf("%d",&i); if(i==1) traverse(sptr1); else if(i==2) traverse(sptr2); else printf("enter correctly"); break; case 4: printf("enter the list no. u wanna copy"); scanf("%d",&i); if(i==1) copy(sptr1,sptr2); else if(i==2) copy(sptr2,sptr1); else { printf("enter correct no."); break; } printf("the copied link list2 is\n"); traverse(sptr2); break; case 5: exit(0); } } while(1); getch(); return 0; }