473,772 Members | 2,388 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Insert a number into a linked list in ascending order

Hello all:

I would like to insert a number into a linked list in ascending order.

Is the following function correct?

void insert(Node **node, int v)
{
Node *tmp = (Node *)malloc(sizeof (Node));
while(*node && (*node)->value < v) node = &(*node)->next;
tmp->value = v;
tmp->next = *node;
*node = tmp;
}

If this is correct, how to answer the following case:

Given a linked-list as follows:
NodeA(2) -NodeB(4) -NodeC(7) -NULL.

Insert 5.

Then the new linked-list will become as follows if I understand
correctly.

NodeA(2) -NodeB(4) -NodeC(7) -NULL
NodeD(5) -NodeC(7)
Please correct me.

Thank you
-Daniel

Jan 24 '07 #1
6 20002
as*******@gmail .com wrote:
I would like to insert a number into a linked list in ascending order.

Is the following function correct?
Probably not, since you're not getting the right result with it :-/
>
void insert(Node **node, int v)
{
Node *tmp = (Node *)malloc(sizeof (Node));
I suggest you *move* 'tmp->value = v;' statement here. And why are
you usuing 'malloc'? It's so much simpler with 'new':

Node *tmp = new Node;

And does your 'Node' class have a constructor? It should, probably.
while(*node && (*node)->value < v) node = &(*node)->next;
tmp->value = v;
tmp->next = *node;
You're not making the "previous" node in the sequence aware of the
insertion. It has to be aware if you want your sequence to run
correctly. (I suppose you have a singly linked list here)

Node *prev = NULL;
while (*node && (*node)->value < v) {
prev = *node;
node = &(*node)->next;
}

if (prev)
prev->next = tmp;
tmp->next = *node;
*node = tmp;
}

If this is correct, how to answer the following case:

Given a linked-list as follows:
NodeA(2) -NodeB(4) -NodeC(7) -NULL.

Insert 5.
What if you insert 1?
>
Then the new linked-list will become as follows if I understand
correctly.

NodeA(2) -NodeB(4) -NodeC(7) -NULL
NodeD(5) -NodeC(7)
Please correct me.
See above. I didn't test it, though.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jan 24 '07 #2
On Jan 24, 3:44 pm, askmat...@gmail .com wrote:
Hello all:

I would like to insert a number into a linked list in ascending order.

Is the following function correct?

void insert(Node **node, int v)
{
Node *tmp = (Node *)malloc(sizeof (Node));
while(*node && (*node)->value < v) node = &(*node)->next;
tmp->value = v;
tmp->next = *node;
*node = tmp;

}
Does not seem right, you forgot to attach the new node to the previous
one.

Given the follownig:

struct Node {
Node* next;
int value;
}

The algorithm would be something like:

void insert(Node* node, int v) {
Node* n = new Node; // use malloc if you want
while (node != 0 && node->next != 0 && node->next->value < v)
node = node->next;
n->value = v;
n->next = node->next;
node->next = n;
}

I think, I have not tried it.

--
Erik Wikström

Jan 24 '07 #3
Hello Victor:

Thank you for your comments and this is the reorganized code:

This is the new code following your comments:

void insert(Node **node, int v) {

Node *tmp = new Node(v);
Node *prev = NULL;

while (*node && (*node)->value < v) {
prev = *node;
node = &(*node)->next;
}

if (prev) // the while loop runs at least once.
{
prev->next = tmp;
tmp->next = *node;
}
else // never enter into the while loop
{
tmp->next = *node;
*node = tmp;
}

} // end of function insert

Hopefully, this time it is correct.
Thank you again:)

Jan 24 '07 #4
Hello Erik:

The original code was written by me and I got it somewhere.
Given the follownig:

struct Node {
Node* next;
int value;

}The algorithm would be something like:

void insert(Node* node, int v) {
Node* n = new Node; // use malloc if you want
while (node != 0 && node->next != 0 && node->next->value < v)
node = node->next;
n->value = v;
n->next = node->next;
node->next = n;

}I think, I have not tried it.

This solution doesn't work if you have a linked-list as follows:

NodeA(7) -NULL;
insert 6 to this linked-list.

Based on your solution, the produced Linked-List will be
NodeA(7) -NodeB(6) -NULL;
I have posted a new solution and wish it is right.

Thank you for your comments.
-Daniel

Jan 24 '07 #5
In article <11************ **********@k78g 2000cwa.googleg roups.com>,
as*******@gmail .com wrote:
Hello all:

I would like to insert a number into a linked list in ascending order.

Is the following function correct?

void insert(Node **node, int v)
{
Node *tmp = (Node *)malloc(sizeof (Node));
while(*node && (*node)->value < v) node = &(*node)->next;
tmp->value = v;
tmp->next = *node;
*node = tmp;
}
What happened when you tested it? For example, what happens with the
following main? (You may need to #include <cassert)

int main()
{
Node* n = 0;
insert( &n, 2 );
assert( n->value == 2 );
assert( n->next == 0 );

insert( &n, 4 );
assert( n->value == 2 );
assert( n->next->value == 4 );
assert( n->next->next == 0 );

insert( &n, 7 );
assert( n->value == 2 );
assert( n->next->value == 4 );
assert( n->next->next->value == 7 );
assert( n->next->next->next == 0 );

insert( &n, 5 );
assert( n->value == 2 );
assert( n->next->value == 4 );
assert( n->next->next->value == 5 );
assert( n->next->next->next->value == 7 );
assert( n->next->next->next->next == 0 );

}
If this is correct, how to answer the following case:

Given a linked-list as follows:
NodeA(2) -NodeB(4) -NodeC(7) -NULL.

Insert 5.

Then the new linked-list will become as follows if I understand
correctly.

NodeA(2) -NodeB(4) -NodeC(7) -NULL
NodeD(5) -NodeC(7)
You answer it however you think it should be answered. Does the problem
require the insert function to maintain a sorted list? What should the
insert function do if the list passed in wasn't sorted in the first
place?

Ask your instructor to please show his students how to test their code
so they will know, before turning it in, if it is correct.

I've tutored several people going to several different colleges, and it
always amazes me that not one of the teachers seem to bother teaching
their students how to test code for conformance to the spec.
Jan 24 '07 #6
"Victor Bazarov" <v.********@com Acast.netwrote:
If this is correct, how to answer the following case:

Given a linked-list as follows:
NodeA(2) -NodeB(4) -NodeC(7) -NULL.

Insert 5.

What if you insert 1?
int main()
{
Node* n = 0;
insert( &n, 4 );
assert( n->value == 4 );
assert( n->next == 0 );

insert( &n, 1 );
assert( n->value == 1 );
assert( n->next->value == 4 );
assert( n->next->next == 0 );
}

None of the asserts fire with his original code.

Granted, the use of malloc in a c++ program is odd, and he would
probably be better off with some member-functions. However, his initial
code passed every test I could think of.
Jan 24 '07 #7

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

Similar topics

5
2328
by: Darryl B | last post by:
I can not get anywhere on this project I'm tryin to do. I'm not expecting any major help with this but any would be appreciated. The assignment is attached. The problem I'm having is trying to set up the class link and tel_list. I set up a class person with strings for name, town, and number. I just don't know how to set up the classes w/ their methods (constructors and operations). I'm stuck on the assignment operator and the add and...
6
3107
by: massimo | last post by:
Hey, I wrote this program which should take the numbers entered and sort them out. It doesn¹t matter what order, if decreasing or increasing. I guess I'm confused in the sorting part. Anyone has any advices?? #include <iostream> using namespace std;
0
935
by: Maurice | last post by:
how could you pass the head from a linked list class so that it could be used in a main file? here is the content of the linkedlist.h file: #ifndef LINKEDLIST_H #define LINKEDLIST_H //******************************************************************
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>
4
2074
by: Peter Schmitz | last post by:
Hi, in my application, I defined a linked list just as follows: typedef struct _MYLIST{ int myval; void *next; }MYLIST; MYLIST head;
6
2071
by: Joe Estock | last post by:
I'm attempting to sort a doubly linked list at the time that an item is added. When I add the items in increasing order everything works correctly, however when I add them in reverse order the correlation is messed up. The list, however, is sorted except for element 0 (or whatever value was the first to be added). I've been working on this most of the night so maybe I am overlooking something. Any help would be much appreciated. Below is a...
19
2534
beacon
by: beacon | last post by:
As you can probably tell from the title, I'm a little frustrated with linked lists. I'm working on a homework assignment and it just isn't making sense to me. I've read and read and read on the subject and I've checked out sample code, but I can't for the life of me get to methods in my class to work, let alone make sense. I've talked to my professor and to tutors at school, but I'm no better now than I was 2 weeks ago when the program was...
3
1500
by: Alien | last post by:
Hi I am having some problems with the annoying segmentation error when I try to run a program that creates a linked list of numbers that are passed on to it. All I am trying to do is to create a link list which takes number that may not possibly be in order. For example, I try to read a file which says, 101 102 105 104 103 101 <-------- Duplication
5
1642
by: WarmDismalAgony | last post by:
hey, can anyone figure out why this insert function is setting all nodes in the list to have the same item? void insert_list (list_ref list, list_item item) { listnode_ref new = malloc (sizeof (struct listnode)); assert (is_list (list)); assert (new != NULL); new->tag = listnode_tag; new->item = item; if (list->head == NULL) { list->head = new;
0
9621
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
9454
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
10106
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
10039
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
9914
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
8937
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...
1
7461
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...
1
4009
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
2851
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.