We help IT Professionals succeed at work.

Ordered linked list?

Methos526 asked
I am trying to create a function that will act on a linked list by creating a new node with the data I pass to it, and then will put it in the right spot in the list. The nodes each have two int variables and a pointer.

struct node(
  int datavalStart;
  int datavalEnd;
  struct node *nextptr;

The nodes must be in increasing order, with a nodes datavalStart value being larger then the datavalEnd of the node before it. Much thanks.
Watch Question

If your teacher allows you to let others make your homework, i will do it for 50 points
May be you can post a piece of code you have tried, or a kind of pseudocode.


I would not be asking about my homework. It is part of a larger project that I am just having trouble with. I can't get past this point so I can't continue. I have all the code in fact, except for the while statement that I think you need to do it. I have a while statement that works for characters as it compares the string with the stdlib function that compares them. I just really need to know how to make this statement with int variabels.
When you are inserting a new node in the list you should walk the chain - start at the head of the list and read each structure using the next pointer in each structure read.

As you read a particular structure from the list you should also read the next in the list using the next pointer in that structure. Once you have read the two structures you can compare the start and end values and compare them to the values in the data you wish to insert.

If the values are such that the end value for the first struct read is less than the start value of the data to be inserted and the end value of the data to be inserted is less than the start value of the second structure read then you know that your data should be inserted between the first and second structures read.

This is done by allocating memory for the data to be inserted, setting the next pointer of the first structure to the address of your new data area and setting the next pointer in your new structure to the address of the second structure you read previously.

If this is not the case you keep walking until it is true or until you hit the end of the list in which case you tack the new data on the end of the list.

You need to think about what you do if you have range overlaps or identical values in a number of structures.

Cheers - Gavin

Explore More ContentExplore courses, solutions, and other research materials related to this topic.