473,836 Members | 2,012 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Creating Linked List using Recursion

34 New Member
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 8656
horace1
1,510 Recognized Expert Top Contributor
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
Suyash Upadhyay
34 New Member
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 Recognized Expert New Member
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
Suyash Upadhyay
34 New Member
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 Recognized Expert Top Contributor
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 Recognized Expert Specialist
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
2383
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, but in PHP, I'm a bit stumped. What I have is a list of simple, small arrays. I'd like to figure out the appropriate data structure so that each element knows which element is it's "parent," and so that each element can have multiple children....
5
7963
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' => 'aaa') , array( 'id' => 'B', 'parent_id' => 'A', 'value' => 'bbb') , array( 'id' => 'C', 'parent_id' => 'B', 'value' => 'ccc') , array( 'id' => 'D', 'parent_id' => 'A', 'value' => 'ddd')
33
1837
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 the characters in reverse order.
4
2935
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 traversal only in one direction, I would say that using appropriate loops/recursion, traversal in opposite direction is also possible. Then why the need for doubly linked list? --
7
1420
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 the user about the data and then do some operations like sorting etc. I decided to use a linked list. The code looks as follows: #include<stdio.h> #include<string.h> #include<stdlib.h>
22
8050
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 solution. Being that recursion is frowned upon in embedded software, the answer was not what the interviewer expected, but alas it was correct. I asked some friends how they would have answered and another answer is to reverse the list and then...
6
4162
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 try my own small program. The problem is, I seem to be having trouble with memory, i.e. sometimes my program will work and display the correct output, and sometimes it will not and display garbage (in a printf call) so i assume i have been using...
9
14509
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. Here is my code node* Reverse_List(node *p) { /*Is there any problem with this statement */ static node *head = p;
0
9812
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9658
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10824
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10244
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9362
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5644
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5813
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4443
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3103
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.