473,785 Members | 2,916 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

linked list error

hi,
i have written a function in adding a node to the linked list
but this only adds "1" to the list as i get in the output
I'm using borland c++ compiler

The code
-------------------------------------------------------------
#include <alloc.h>
#include <stdio.h>
#include <string.h>
void append(struct node **, int );
void display(struct node *);
struct node
{
int data;
struct node *link;
};
void main()
{
struct node *p;
p = NULL;
//printf("the number of elements in the linked list are: = %d",
count(p));
append(&p, 1);
append(&p, 5);
append(&p, 17);
display(p);
}
void append(struct node **q, int num)
{
struct node *temp, *r;
temp = *q;
if (*q == NULL)
{
temp = (struct node *)malloc(sizeof (struct node));
temp->data = num;
temp->link = NULL;
*q = temp;
}
else
{
//temp = *q;
while(temp->link!=NULL)
{
r = (struct node *)malloc(sizeof (struct node));
r->data =num;
r->link = NULL;
temp->link = r;
}
}
}
void display(struct node *q)
{
while(q!=NULL)
{
printf("%d", q->data);
q = q->link;
}
}
-------------------------------------------------------

Thanks

Pradyut
http://pradyut.tk
http://groups.yahoo.com/group/d_dom/
http://groups-beta.google.com/group/oop_programming
India

Nov 14 '05 #1
4 2265
PRadyut wrote:

i have written a function in adding a node to the linked list
but this only adds "1" to the list as i get in the output
I'm using borland c++ compiler

The code
-------------------------------------------------------------
#include <alloc.h>
No such standard include
#include <stdio.h>
#include <string.h>

void append(struct node **, int );
void display(struct node *);
struct node
{
int data;
struct node *link;
};
void main()


illegal. main returns int. Say so.

Since you already have some fatal errors, snip code. Here is some
code that works as is. Go ahead and study it and/or modify it to
taste.

/* A simplified demo of creating a linked list */
/* EOF or a non-numeric entry ends entry phase */

#include <stdio.h>
#include <stdlib.h>

typedef int datatype;

struct node {
struct node *next;
datatype datum;
};

/* ----------------- */

/* add value to head of list */
struct node *addtolist(stru ct node *root, datatype value)
{
struct node *newnode;

if ((newnode = malloc(sizeof *newnode))) {
newnode->next = root;
newnode->datum = value;
}
return newnode;
} /* addtolist */

/* ----------------- */

void showlist(struct node *root)
{
while (root) {
printf("%d\n", root->datum);
root = root->next;
}
} /* showlist */

/* ----------------- */

/* believed necessary and sufficient for NULL terminations */
/* Reverse a singly linked list. Reentrant (pure) code */
struct node *revlist(struct node *root)
{
struct node *curr, *nxt;

if (root) { /* non-empty list */
curr = root->next;
root->next = NULL; /* terminate new list */
while (curr) {
nxt = curr->next; /* save for walk */
curr->next = root; /* relink */
root = curr; /* save for next relink */
curr = nxt; /* walk onward */
}
}
/* else empty list is its own reverse; */
return root;
} /* revlist */

/* ----------------- */

int main(void)
{
struct node *root, *tmp;
datatype num;

root = NULL;
while (1 == scanf("%d", &num)) {
if ((tmp = addtolist(root, num))) root = tmp;
else break;
}
showlist(root);
root = revlist(root);
showlist(root);
return 0;
} /* main linklist.c */

--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
Nov 14 '05 #2


PRadyut wrote:
hi,
i have written a function in adding a node to the linked list
but this only adds "1" to the list as i get in the output
I'm using borland c++ compiler

The append function is badly flawed. You need to rethink the
logic and make it simple. Your goal is to append a new node
at the tail of the list. As you traverse to the tail, for one,
you do not want to malloc memory each time in the loop. See
one possible definition of function append below.
The code
-------------------------------------------------------------
#include <alloc.h>
Make this
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void append(struct node **, int );
void display(struct node *);
struct node
{
int data;
struct node *link;
};
void main()
int main(void)
{
struct node *p;
p = NULL;
append(&p, 1);
append(&p, 5);
append(&p, 17);
display(p);

Write a function to free the allocated space once you
are finished with it.

return 0;
}
void append(struct node **q, int num)
This function is redefined below.
{
struct node *temp, *r;
temp = *q;
if (*q == NULL)
{
temp = (struct node *)malloc(sizeof (struct node));
temp->data = num;
temp->link = NULL;
*q = temp;
}
else
{
//temp = *q;
while(temp->link!=NULL)
{
r = (struct node *)malloc(sizeof (struct node));
r->data =num;
r->link = NULL;
temp->link = r;
}
}
}
void display(struct node *q)
{
while(q!=NULL)
{
printf("%d", q->data);
printf("%d\n",q->data);
q = q->link;
}
}

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

struct node *append(struct node **, int );
void display(struct node *);
void freenodes(struc t node *);

struct node
{
int data;
struct node *link;
};
int main(void)
{
struct node *p;
p = NULL;
append(&p, 1);
append(&p, 5);
append(&p, 17);
display(p);
freenodes(p);
return 0;
}

struct node *append(struct node **q, int num)
{
struct node **temp, *newnode;

if((newnode = malloc(sizeof *newnode)) != NULL)
{
newnode->data = num;
newnode->link = NULL;
for(temp = q; *temp; temp = &(*temp)->link) ;
*temp = newnode;
}
return newnode;
}

void display(struct node *q)
{
while(q!=NULL)
{
printf("%d\n", q->data);
q = q->link;
}
return;
}

void freenodes(struc t node *q)
{
struct node *temp;

for( ; (q) ; q = temp)
{
temp = q->link;
free(q);
}
return;
}

--
Al Bowers
Tampa, Fl USA
mailto: xa******@myrapi dsys.com (remove the x to send email)
http://www.geocities.com/abowers822/

Nov 14 '05 #3
just a little change, i would be happy
thanks all for your help

in the append function there should be

while(temp->link!=NULL)
temp = temp->link;
r = (struct node *)malloc(sizeof (struct node));
r->data =num;
r->link = NULL;
temp->link = r;

Nov 14 '05 #4


PRadyut wrote:
just a little change, i would be happy
thanks all for your help

in the append function there should be

while(temp->link!=NULL)
temp = temp->link;
r = (struct node *)malloc(sizeof (struct node));
r->data =num;
r->link = NULL;
temp->link = r;

I assume this represents a change in the 'else' branch.
You must take into account that the function malloc may fail
and return a value of NULL which indicates space was not
allocated. You need to check for this before you assign.
If space is allocated, assign and place the node in the list.
If not, you will need to exit gracefully from the function
giving some indication that a new new node was not added.
this is done by checking the return value of function append.

struct node *append(struct node **q, int num)
{
struct node *temp, *r;
temp = *q;

if((r = malloc(sizeof *r)) != NULL)
{
r->data = num;
r->link = NULL;
if (*q == NULL) *q = r;
else
{
while(temp->link!=NULL)
temp = temp->link;
temp->link = r;
}
}
return r;
}

--
Al Bowers
Tampa, Fl USA
mailto: xa******@myrapi dsys.com (remove the x to send email)
http://www.geocities.com/abowers822/

Nov 14 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
4603
by: Steve Lambert | last post by:
Hi, I've knocked up a number of small routines to create and manipulate a linked list of any structure. If anyone could take a look at this code and give me their opinion and details of any potential pitfalls I'd be extremely grateful. Cheers Steve
12
15100
by: Eugen J. Sobchenko | last post by:
Hi! I'm writing function which swaps two arbitrary elements of double-linked list. References to the next element of list must be unique or NULL (even during swap procedure), the same condition should be kept for references to previous element of list. Here is my solution below: struct node {
4
3604
by: JS | last post by:
I have a file called test.c. There I create a pointer to a pcb struct: struct pcb {   void *(*start_routine) (void *);   void *arg;   jmp_buf state;   int    stack; };   struct pcb *pcb_pointer;
32
5949
by: Clunixchit | last post by:
How can i read lines of a file and place each line read in an array? for exemple; array=line1 array=line2 ...
2
4205
by: PRadyut | last post by:
In this code i tried to add the elements in ascending order but the output is only 0 1 2 the rest of the elements are not shown. the code ---------------------------------------------------------- #include <stdio.h>
3
2712
by: chellappa | last post by:
hi this simple sorting , but it not running...please correect error for sorting using pointer or linked list sorting , i did value sorting in linkedlist please correct error #include<stdio.h> #include<stdlib.h> int main(void) {
6
2244
by: deanfamily | last post by:
I am re-posting my second problem. I have a double-linked list. I need to know if it is possible to remove just one of an item, instead of all that match the given criteria with the remove() command. Any thoughts?
6
2150
by: mattmao | last post by:
Okay, this is just my exercise in order to prepare for the coming assignment regarding the damned Linked List issue... The task is simple and I am about to finish it. However, I couldn't go around one last bit: how to print out the elements? Here is so far what I've got: #include <stdio.h> #include <stdlib.h> struct intRecord
6
4158
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...
7
5773
by: QiongZ | last post by:
Hi, I just recently started studying C++ and basically copied an example in the textbook into VS2008, but it doesn't compile. I tried to modify the code by eliminating all the templates then it compiled no problem. But I can't find the what the problem is with templates? Please help. The main is in test-linked-list.cpp. There are two template classes. One is List1, the other one is ListNode. The codes are below: // test-linked-list.cpp :...
0
9645
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
9480
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
10153
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10093
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9952
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...
1
7500
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5381
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...
1
4053
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
2880
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.