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

Home Posts Topics Members FAQ

how to add at the end of the linked list

hi i am writing the following function . but does not seem to put the code
in sequence. it does not compile. its kind of messed up. please help me
improve it. thanks.

void addToEndOfLinke dList(Node * &head)
// Reads a series of integers from the keyboard (ending with -1) and
// appends them to the end of the linked list pointed to by head. No
// error checking is done. Correctly handles the case when the
// original list starts out empty.

{

int a;
int prev;

cout<<"Enter an integer, -1 to quit:";
cout.flush();

while ((cin >> a) && (a != -1))
if (prev==NULL)

{
Node *newPtr;
Node *newvalue;

newPtr = new Node;
newPtr->item= newvalue;
newPtr->next = NULL;
NULL= newPtr;

}
}

Jul 23 '05 #1
2 2038
chirag wrote:
hi i am writing the following function . but does not seem to put the code
in sequence. it does not compile.
And no error message form the compiler?
its kind of messed up. please help me improve it. thanks.

void addToEndOfLinke dList(Node * &head)
Why do you pass the pointer by reference? You are not writing to it.
Actually, you aren't using the pointer at all in the function.
// Reads a series of integers from the keyboard (ending with -1) and
// appends them to the end of the linked list pointed to by head. No
// error checking is done. Correctly handles the case when the
// original list starts out empty.

{

int a;
int prev;

cout<<"Enter an integer, -1 to quit:";
cout.flush();
No need to flush here. cin and cout are tied together, which means that
reading from cin will automatically flush cout.
while ((cin >> a) && (a != -1))
You're reading your integers here, but you are never using them for anything
except ending the loop.
if (prev==NULL)
prev is uninitialized. Don't ever use variables that haven't been
initialized and haven't been written to before. The value is undefined.
Another thing: Never use NULL in an integer context. It is meant for
pointers only. Actually, it's a good idea to not use NULL at all. Just use
0. Anyway, I'm not sure that prev actually is supposed to be an integer.
What is the purpose of prev?
{
Node *newPtr;
Node *newvalue;

newPtr = new Node;
newPtr->item= newvalue;
Again, newvalue is uninitialized. Also, is newPtr->item really a pointer to
Node? Looks to me as if you actually should assign the variable a to it.
newPtr->next = NULL;
NULL= newPtr;
That last assignment makes no sense. You cannot assign anything to NULL.
What was the intention of that?
Where are you actually appending your new node to the list?
}
}


Jul 23 '05 #2
chirag wrote:
hi i am writing the following function . but does not seem to put the code
in sequence. it does not compile. its kind of messed up. please help me
improve it. thanks.

void addToEndOfLinke dList(Node * &head) Just pass the pointer, no need to pass it by reference.
Is this argument a new node or a pointer to the start of the list?
// Reads a series of integers from the keyboard (ending with -1) and
// appends them to the end of the linked list pointed to by head. No
// error checking is done. Correctly handles the case when the
// original list starts out empty.

{

int a;
int prev;

cout<<"Enter an integer, -1 to quit:";
cout.flush();

while ((cin >> a) && (a != -1))
if (prev==NULL)

{
Node *newPtr;
Node *newvalue;

newPtr = new Node;
newPtr->item= newvalue;
newPtr->next = NULL;
NULL= newPtr;

}
}

Rather than correct your code, here is the generic
code for appending a node to a list:
struct Node
{
Node * next;
};

struct Integer_Node
: public Node
{
int value;
};

void Append_To_List( Node * &list_start,
Node * new_node)
{
/* Make sure that the pointer to the new node is
* not NULL. Bad things happen when dereferencing
* a NULL pointer.
*/
assert(new_node != NULL);

/* As a precaution, set the "next" field of the
* new node to NULL. This may not be necessary,
* but better safe than sorry.
*/
new_node->next = NULL;

if (list_start == NULL)
{
// This is the reason for passing the pointer
// by reference.
list_start = new_node;
}
else
{
Node * prev = list_start;
Node * n = list_start;

/* Search for the end of the list, and maintain
* a pointer to the previous node.
*/
while (n != NULL)
{
prev = n;
n = n->next;
}

/* At this point, "prev" points to the last node
* in the list. Link the new node to the "prev"
* node.
*/
prev->next = n;
}
return;
}

The above function only appends a node to the list.
The creating of a node has been extracted to make
the functionality more generic so it can be used for
programs that create nodes from files, databases, etc,
not just from cin.

Also note that the above function only deals with the
link field and not the value field. That is why I have
separated the two fields into separate classes.

int main(void)
{
Integer_Node * list_head;
Integer_Node * i_node;

cout<<"Enter an integer, -1 to quit:";
cout.flush();

int a;
while ((cin >> a) && (a != -1))
{
i_node = new Integer_Node;
i_node->value = a;
Append_To_List( list_head, i_node);

cout<<"Enter an integer, -1 to quit:";
cout.flush();
}
return 0;
}

--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.l earn.c-c++ faq:
http://www.comeaucomputing.com/learn/faq/
Other sites:
http://www.josuttis.com -- C++ STL Library book
http://www.sgi.com/tech/stl -- Standard Template Library

Jul 23 '05 #3

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

Similar topics

5
7958
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')
11
3101
by: C++fan | last post by:
Suppose that I define the following class: class example_class{ public: example_class(); void funtion_1(); void function_2(); protected:
5
859
by: Dream Catcher | last post by:
1. I don't know once the node is located, how to return that node. Should I return pointer to that node or should I return the struct of that node. 2. Also how to do the fn call in main for that LOCATE subroutine that returns a node???? Any help would be appreciated. Thanks
10
15133
by: Kent | last post by:
Hi! I want to store data (of enemys in a game) as a linked list, each node will look something like the following: struct node { double x,y; // x and y position coordinates struct enemy *enemydata; // Holds information about an enemy (in a game) // Its a double linked list node
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 {
12
3954
by: joshd | last post by:
Hello, Im sorry if this question has been asked before, but I did search before posting and couldnt find an answer to my problem. I have two classes each with corresponding linked lists, list1 and list2, each node within list1 has various data and needs to have a pointer to the corresponding node in list2, but I cant figure out how to do this. Could someone explain what I might be missing, or maybe point me in the direction of a good...
1
15553
by: theeverdead | last post by:
Ok I have a file in it is a record of a persons first and last name. Format is like: Trevor Johnson Kevin Smith Allan Harris I need to read that file into program and then turn it into a linked list. So on the list I can go Trevor, Kevin, Allan in a straight row but I can also call out there last name when I am on their first name in the list. Sorry if it doesn't make sense trying to explain best I can. So far I have // list.cpp
0
8633
by: Atos | last post by:
SINGLE-LINKED LIST Let's start with the simplest kind of linked list : the single-linked list which only has one link per node. That node except from the data it contains, which might be anything from a short integer value to a complex struct type, also has a pointer to the next node in the single-linked list. That pointer will be NULL if the end of the single-linked list is encountered. The single-linked list travels only one...
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
10325
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...
1
10091
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
9950
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
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...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4050
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
2879
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.