473,598 Members | 2,978 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C Linked List -

Hi,

I am writing to ask for some info with a program I am trying out. I
am teaching myself
linked lists in C.

I have a linked list (see code below), and I accept user input which
is the inputted into
the list via an 'insert function'. The users value is passed as a
paramater to 'insert'.
All is ok with this, but what I was wondering is, if I have a node
with say 10 variables instead of one, is it still ok/efficent to pass
these values to 'insert' as paramaters?
Is there another way??

Also, I know that you can delete nodes, but is there any other actions
that can be performed on linked lists that would help me learn more?

Thanks a million,
Ritchie
~~~~~~~~~~~~~~~ ~~~CODE START ~~~~~~~~~~~~~~~ ~~~~
struct node {
int iOrderDate;
struct node *nextPtr;
};
typedef struct node Node;
typedef Node *NodePtr;

/*************** ******* fns *************** **************/

void insert ( NodePtr *, int );

/*************** *************** *************** ***********/
....

void insert (NodePtr *sPtr, int lDate)
{
NodePtr newPtr, prevPtr, currPtr;

newPtr = malloc( sizeof(Node) );

if( newPtr != NULL )
{
newPtr->iOrderDate = lDate;
newPtr->nextPtr = NULL;

prevPtr = NULL;
currPtr = *sPtr;

while( currPtr != NULL && lDate > currPtr->iOrderDate )
{
prevPtr = currPtr;
currPtr = currPtr->nextPtr;
}

if( prevPtr == NULL )
{
newPtr->nextPtr = *sPtr;
*sPtr = newPtr;
}
else
{
prevPtr->nextPtr = newPtr;
newPtr->nextPtr = currPtr;
}
}
else
printf("unable to allocate memory!");
}

~~~~~~~~~~~~~~C ODE END ~~~~~~~~~~~~~~~ ~~
Nov 14 '05 #1
7 7708
ritchie wrote:
Hi,

I am writing to ask for some info with a program I am trying out. I
am teaching myself
linked lists in C.

I have a linked list (see code below), and I accept user input which
is the inputted into
the list via an 'insert function'. The users value is passed as a
paramater to 'insert'.
All is ok with this, but what I was wondering is, if I have a node
with say 10 variables instead of one, is it still ok/efficent to pass
these values to 'insert' as paramaters?
Is there another way??
If I understand you, there should be no difference how many members Node
has, because you're passing it as a pointer.

Also, I know that you can delete nodes, but is there any other actions
that can be performed on linked lists that would help me learn more?
Not that I can think of, although a function to walk the list, accepting a
function pointer as an argument, and calling the pointed-to function for
each node (passing the node) could be handy.

[snip]
Nov 14 '05 #2
ritchie wrote:

Hi,

I am writing to ask for some info with a program I am trying out. I
am teaching myself
linked lists in C.
Please fix your line lengths, go with something less than 80 character
so that weird wrapping like the above does not occur.

All is ok with this, but what I was wondering is, if I have a node
with say 10 variables instead of one, is it still ok/efficent to pass
these values to 'insert' as paramaters?
That's starting to push it from a readability standpoint. I doubt it
makes a significant difference in performance.
Is there another way??
Sure, create the new node and pass a pointer to the insert function.
Also, I know that you can delete nodes, but is there any other actions
that can be performed on linked lists that would help me learn more?

One of the obvious important ones is to find a specific node based on
search criteria. My linked list stuff also has a replace_node() function
to swap out a node. I also have print_node() that outputs the node data,
and a dump_list() which prints out the data from the entire list in one
fell swoop.

A lot of the functionality you add will depend on what you use the list
for.

Brian Rodenborn
Nov 14 '05 #3
ritchie wrote:
Hi,

I am writing to ask for some info with a program I am trying out. I
am teaching myself
linked lists in C.

I have a linked list (see code below), and I accept user input which
is the inputted into
the list via an 'insert function'. The users value is passed as a
paramater to 'insert'.
All is ok with this, but what I was wondering is, if I have a node
with say 10 variables instead of one, is it still ok/efficent to pass
these values to 'insert' as paramaters?
Is there another way??

Also, I know that you can delete nodes, but is there any other actions
that can be performed on linked lists that would help me learn more?

Thanks a million,
Ritchie
~~~~~~~~~~~~~~~ ~~~CODE START ~~~~~~~~~~~~~~~ ~~~~
struct node {
int iOrderDate;
struct node *nextPtr;
};
typedef struct node Node;
typedef Node *NodePtr;

[snip]

I would isolate the data from the links. Try to make the
link list container independent of the data in the container.

For example:
struct node
{
void * p_data;
struct node * next;
};

typedef int (*P_Compare_Fun c)(void * p_A, void * p_B);

Also, to make the list more generic, provide these functions:
insert_front (a.k.a. push_front) -- add to front of list.
insert_back (a.k.a. push_back) -- append to list.
insert_sort(str uct node * p_list,
void * data,
P_Compare_Func compare_func);
The insert_sort function would use the function pointer
to find out where to insert the new node.

By using a pointer to the data, the number of parameters
for the insert functions is the same regardless of how
many variables are "in the node".

--
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.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book

Nov 14 '05 #4

"ritchie" <ri*********@ya hoo.com> wrote in message

All is ok with this, but what I was wondering is, if I have a node
with say 10 variables instead of one, is it still ok/efficent to pass
these values to 'insert' as paramaters?
Is there another way??
The rule of thumb is that you should pass no more than four parameters to a
function. This is because, internally, most compilers will pass up to four
parameters in registers, whilst additional ones will be passed on the stack,
which is slower. The other reason is that four parameters is about as many
as the human eye can cope with.
However if you really need extra parameters, this rule can be broken.
As many as ten parameters are probaly best wrapped up in a structure. struct node {
int iOrderDate;
struct node *nextPtr;
};
typedef struct node Node;
typedef Node *NodePtr;
Personally I hate this. Node * tells you that a pointer is being passed.
Typedef the asterisk away, and you rapidly end up with a situation where you
don't know what is going on.

I notice you call malloc() to allocate new nodes. This is acceptable, but to
squeeze extra performance you could consider writing your own fixed-size
allocator / deallocator. Use the link to keep track of your free store.
Initally, all entries are free and the list is set so each points to its
neighbour. To allocate, return the first on the list and advance your free
pointer. To free, set the link in the block to be freed to your free
pointer, and set the free pointer to the block just freed.


Nov 14 '05 #5
Hi,

Thanks for the replies.
However, I have another question about linked lists.

I am getting the values for the nodes by sannf'ing them into variables
in main and then passing those variables into the insert function.
Is this the correct way to do it? As I have seem it done differently
before, scanf'ed directly into the node.
ie: "scanf("%d" , nodePtr->nodeMember); ".
Does it make a difference?

Also, I am trying to insert a date but i'm not quite sure what is the
best way to do it.

I have included code below which is inserting the values, but i'm not
quite sure that i'm doing it correctly.

If anyone has time could they please let me know if/what i'm doing
wrong?

Thanks again,
Ritchie

*************** *************co de************* *************** **
struct date {
int iDay;
int iMonth;
int iYear;
};
typedef struct date Date;

struct node {
Date iOrderDate;
char cType[20];
struct node *nextPtr;
};
typedef struct node Node;
typedef Node *NodePtr;
….
/*************** ******** FUNCTIONS****** *************** *********/
void insert ( NodePtr *, int , char[] );
/*************** *************** *************** *************** *****/
int main(void) {
int iDateIn=0;
char cTypeIn[20];
....
printf("Enter date: "); scanf( "%d", & iDateIn);//GET VALUES TO
INSERT
printf("Enter type: "); scanf( "%s", cTypeIn );

insert( &nStart, iDateIn, cTypeIn ); //INSERT INTO NODE

/*************** ********** insert fn *************** *************** **/
void insert( NodePtr *sPtr, int lOrderDate, char lType[] )
{
NodePtr newPtr, prevPtr, currPtr;
newPtr = malloc( sizeof(Node) );

if( newPtr != NULL )
{
newPtr->iOrderDate.iDa y = lOrderDate;
newPtr->nextPtr = NULL;

prevPtr = NULL;
currPtr = *sPtr;

while( currPtr != NULL && lOrderDate > currPtr-iOrderDate.iDay )
{
prevPtr = currPtr;
currPtr = currPtr->nextPtr;
}
if( prevPtr == NULL )
{
newPtr->nextPtr = *sPtr;
*sPtr = newPtr;
}
else
{
prevPtr->nextPtr = newPtr;
newPtr->nextPtr = currPtr;
}
}
else
printf("unable to allocate memory!");
}
Nov 14 '05 #6
ritchie wrote:

Hi,

Thanks for the replies.
However, I have another question about linked lists.

I am getting the values for the nodes by sannf'ing them into variables
in main and then passing those variables into the insert function.
Is this the correct way to do it? As I have seem it done differently
before, scanf'ed directly into the node.
ie: "scanf("%d" , nodePtr->nodeMember); ".
Does it make a difference?

Also, I am trying to insert a date but i'm not quite sure what is the
best way to do it.

I have included code below which is inserting the values, but i'm not
quite sure that i'm doing it correctly.

If anyone has time could they please let me know if/what i'm doing
wrong?


Why don't you post a small complete program ?

--
pete
Nov 14 '05 #7
Hi,

Thanks everyone for the replies. They have all been very helpful.

I have included most of my program.
I am calling these functions from a menu, which is where I suspect
that the trouble may lie?

The problem is that now, when I printf out the values, I keep getting
only the last values entered, and not the rest.
Can anyone see where i'm going wrong?

Also for my insert function, the values are going in, in any order.
What would be the best way to insert or display these values in
ascending/descending order?

Thanks again,
Ritchie
struct date {
int day;
int month;
int year;
};
typedef struct date Date;
struct node {
Date ord_date;
char type[20];
int num;
int num2;
int num3;
struct node *nextPtr;
};

int insert( struct node * indexArr[] )
{
size_t i, j;
struct node *pPtr, *prevPtr;

for (i = 0; i < 5; i++) {
indexArr[i] = prevPtr = NULL;

for (j = 0; j < 5; j++) {
pPtr = malloc(sizeof(s truct node));

if (pPtr != NULL)
{
if (j == 0)
indexArr[i] = pPtr;
//? printf("enter type: "); scanf("%s", &(pPtr->type));
printf("enter num: "); scanf("%d", &(pPtr->num));
printf("enter num2: "); scanf("%d", &(pPtr->num2));
printf("enter num3: "); scanf("%d", &(pPtr->num3));
pPtr->nextPtr = NULL;

if (prevPtr)
prevPtr->nextPtr = pPtr;
prevPtr = pPtr;
}
else
{
return 0;
}
}
}
return;
}


pete <pf*****@mindsp ring.com> wrote in message news:<40******* ****@mindspring .com>...
ritchie wrote:

Hi,

Thanks for the replies.
However, I have another question about linked lists.

I am getting the values for the nodes by sannf'ing them into variables
in main and then passing those variables into the insert function.
Is this the correct way to do it? As I have seem it done differently
before, scanf'ed directly into the node.
ie: "scanf("%d" , nodePtr->nodeMember); ".
Does it make a difference?

Also, I am trying to insert a date but i'm not quite sure what is the
best way to do it.

I have included code below which is inserting the values, but i'm not
quite sure that i'm doing it correctly.

If anyone has time could they please let me know if/what i'm doing
wrong?


Why don't you post a small complete program ?

Nov 14 '05 #8

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

Similar topics

11
3084
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
15113
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
4591
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
15083
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
3939
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...
51
8608
by: Joerg Schoen | last post by:
Hi folks! Everyone knows how to sort arrays (e. g. quicksort, heapsort etc.) For linked lists, mergesort is the typical choice. While I was looking for a optimized implementation of mergesort for linked lists, I couldn't find one. I read something about Mcilroy's "Optimistic Merge Sort" and studied some implementation, but they were for arrays. Does anybody know if Mcilroys optimization is applicable to truly linked lists at all?
1
15522
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
8619
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
5760
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
7981
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
7894
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
8284
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
8392
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...
0
8262
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
6711
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
5847
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
5437
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
1245
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.