473,320 Members | 2,041 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Creating Linked List using Recursion

Hi All,
As a beginner in Computer Programming, I decided to create Linked List using recursion, but I am not getting right answer. I think it is fundamentally correct, but I am stuck.
Please help me,


Expand|Select|Wrap|Line Numbers
  1. #include "stdio.h"
  2.  
  3. struct node
  4. {
  5.     int n;
  6.     struct node* link;
  7. };
  8.  
  9. struct node* node1=NULL;
  10. struct node* node2=NULL;
  11.  
  12. void create();
  13.  
  14. main()
  15. {
  16.     char c;
  17.     printf("Do you want to create a linked list? ");
  18.     scanf("%c",&c);
  19.     if(c=='y')
  20.         create();
  21.     //Displaying Elements of the Linked List
  22.     while(node2!=NULL)
  23.     {
  24.         printf("%d",node2->n);
  25.         node2=node2->link;
  26.     }    
  27. }
  28.  
  29.  
  30. void create()
  31. {
  32.     struct node a;
  33.     char ch;
  34.     if(node1==NULL)
  35.     {
  36.         printf("\nEnter the Integer Value: ");
  37.         scanf("%d",&(a.n));
  38.         a.link=NULL;
  39.         node1=&a;
  40.         node2=&a;
  41.     }
  42.     else
  43.     {
  44.         printf("\nEnter the Integer Value: ");
  45.         scanf("%d",&(a.n));
  46.         a.link=NULL;
  47.         node1->link=&a;
  48.         node1=node->link;
  49.     }
  50.     printf("\nDo you want to enter more elements in linked list? ");
  51.     scanf("%s",&ch);
  52.     if(ch=='n')
  53.         return;
  54.     else
  55.         create();
  56. }
Thanx

Suyash.Upadhyay
Mar 25 '07 #1
6 8606
horace1
1,510 Expert 1GB
in create()
Expand|Select|Wrap|Line Numbers
  1. void create()
  2. {
  3.     struct node a;
  4.  
a is a local variable which is lost on function exit.
make a a pointer and use malloc() to allocate storage, e.g.
Expand|Select|Wrap|Line Numbers
  1. void create()
  2. {
  3.     struct node *a=malloc(sizeof(struct node));
  4.     char ch;
  5.     if(node1==NULL)
  6.     {
  7.         printf("\nEnter the Integer Value: ");
  8.         scanf("%d",&(a->n));
  9.         a->link=NULL;
  10.         node1=a;
  11.         node2=a;
  12.     }
  13. ... etc etc
  14.  
Mar 25 '07 #2
Thanx,
I got right Output, but can you please clarify one doubt:-


Structure is user defined data type, so when we instatiate it some space in memory should be get allocated for that variable( just like when we declare int a; some space allocates for a), then why should we explicitly use malloc function.
Please help me,


Suyash.Upadhyay
Mar 26 '07 #3
svlsr2000
181 Expert 100+
Thanx,
I got right Output, but can you please clarify one doubt:-


Structure is user defined data type, so when we instatiate it some space in memory should be get allocated for that variable( just like when we declare int a; some space allocates for a), then why should we explicitly use malloc function.
Please help me,


Suyash.Upadhyay
there are four scopes in c, in general
block, function, file and program scope. some people refer global scope as program scope.
At the end of scope usually the variable space or memory occupied by variable is freed and returned to operating system. (for this reason usually these variables are stored in stack)
Memory allocated by malloc are from heap and this persist between function calls(unless you free them using free()).
Mar 26 '07 #4
there are four scopes in c, in general
block, function, file and program scope. some people refer global scope as program scope.
At the end of scope usually the variable space or memory occupied by variable is freed and returned to operating system. (for this reason usually these variables are stored in stack)
Memory allocated by malloc are from heap and this persist between function calls(unless you free them using free()).


Thanx but I have still a problem.

In my program node2 is defined in program scope.I have printed node->n immediately after assignment of node2=&a ( where a is an instance of structure)
it gives right result, but when I tried to print node2->n just outside that block it always gives result as 0. What's the problem with it. Please have a glance at my code.

Expand|Select|Wrap|Line Numbers
  1. #include "stdio.h"
  2.  
  3. struct node
  4. {
  5.     int n;
  6.     struct node* link;
  7. };
  8.  
  9. struct node* node1=NULL;
  10. struct node* node2=NULL;
  11. struct node* node3;
  12.  
  13. void create();
  14.  
  15. main()
  16. {
  17.     char c;
  18.     printf("Do you want to create a linked list? ");
  19.     scanf("%c",&c);
  20.     if(c=='y')
  21.         create();
  22. }
  23.  
  24.  
  25. void create()
  26. {
  27.     struct node a;
  28.     char ch;
  29.     if(node1==NULL)
  30.     {
  31.         printf("\nEnter the Integer Value: ");
  32.         scanf("%d",&(a.n));
  33.         a.link=NULL;
  34.         node1=&a;
  35.         node2=&a;
  36.         printf("\nTesting1 %d",node2->n);
  37.     }
  38.     else
  39.     {
  40.         printf("\nEnter the Integer Value: ");
  41.         scanf("%d",&(a.n));
  42.         a.link=NULL;
  43.         node1->link=&a;
  44.         node1=node1->link;
  45.         printf("\nTesting2 %d",node1->n);
  46.     }
  47.     printf("\nDo you want to enter more elements in linked list? ");
  48.     scanf("%s",&ch);
  49.     printf("\nTesting2.5 %d",node2->n);  //it gives output 0
  50.     if(ch=='n')
  51.         return;
  52.     else
  53.     {
  54.         printf("\nTesting3 %d",node2->n);
  55.         while(node3!=NULL)
  56.         {
  57.             printf("\nTesting4 %d",node2->n);  // always prints 0
  58.             printf("\n");
  59.             node3=node3->link;
  60.         }
  61.         create();
  62.     }
  63. }

Please help me.

Suyash.Upadhyay
Mar 26 '07 #5
horace1
1,510 Expert 1GB
in the following you read ch which is a char using conversion specification %s which is for a string
Expand|Select|Wrap|Line Numbers
  1.     printf("\nDo you want to enter more elements in linked list? ");
  2.     scanf("%s",&ch);
  3.  
and you are corrupting memory
change the conversion specification to %c to read a char
Expand|Select|Wrap|Line Numbers
  1.     printf("\nDo you want to enter more elements in linked list? ");
  2.     getchar(); // read last newline
  3.     scanf("%c",&ch);
  4.     printf("\nTesting2.5 %d",node2->n);  //it gives output 0
  5.  
you need the getchar() to remove the newline entered after the last integer value
Mar 26 '07 #6
Ganon11
3,652 Expert 2GB
In my program node2 is defined in program scope.I have printed node->n immediately after assignment of node2=&a ( where a is an instance of structure)
it gives right result, but when I tried to print node2->n just outside that block it always gives result as 0. What's the problem with it.
In the function, you have created a node a with function scope. Then you have node2 point to this temporary node - during the function, node2 is properly defined and will act as planned. But as soon as the function exits, the node created by a is de-allocated. Suddenly, node2 points to de-allocated (a.k.a. useless) memory.

If you are using C++, you should create a node object for node2 using the new operator. If you are using C, you should create a node object using malloc.
Mar 26 '07 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: M. Katz | last post by:
I'm trying to create a heirarchical linked list of sorts, and I'm looking for advice as to how best to set up the arrays. In other languages, I might use a pointer array to other pointer arrays,...
5
by: Jeffrey Silverman | last post by:
Hi, all. I have a linked list. I need an algorithm to create a tree structure from that list. Basically, I want to turn this: $list = array( array( 'id' => 'A', 'parent_id' => null, 'value'...
33
by: junky_fellow | last post by:
Consider a singly-linked list. Each node has a structure, struct node { char c; struct node *next; }; Each of the nodes contain an alphabetic character. Can anybody suggest a way to print...
4
by: dssuresh6 | last post by:
Whether browsing forward or backward can be done using a singly linked list. Is there any specific case where a doubly linked list is needed? For people who say that singly linked list allows...
7
by: alternativa | last post by:
Hello, I'm a beginner in C programming and I have a problem that probably will seem trivial to most of you, however I can't find a solution... So, I have to write a data base - program should ask...
22
by: joshc | last post by:
In an interview for an embedded software position recently I was asked to write code, in C, for printing the contents of a linked list backwards. After a few minutes I came up with the recursive...
6
by: tgnelson85 | last post by:
Hello, C question here (running on Linux, though there should be no platform specific code). After reading through a few examples, and following one in a book, for linked lists i thought i would...
9
by: DanielJohnson | last post by:
Hi, I am not seeking a solution nor am I asking a homework problem. I have my solution but it doesn't run correctly as expected because of some error and I am trying to understand this error....
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.