473,396 Members | 1,933 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Linked List Question

beacon
579 512MB
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 assigned.

Here's the gist:

1) I have to create a linked list that will sort in ascending or descending order based on the user's input and it has to be in a class. The list will read in data from a file that will be named at runtime(???). If it is not named it will get a generic filename.

2) I have to create an append method that will place a new node at the end of the list.

3) I have to create an insert method that will place a new node in the correct order (ascending or descending) in the list.

4) I have to create a print method to output the data.

First off, I have no idea what should go in my constructor. Should I prompt the user to enter 'd' or 'a' and then call the constructor based on their input?

Secondly, I can't get the insert method to work to save my life. I keep getting lost in an infinite loop and don't know why.

Anyway, here's my code so far if anyone would like to help.

Thanks...

Expand|Select|Wrap|Line Numbers
  1. //*** MAIN ***
  2. #include <iostream>
  3. #include <fstream>
  4. #include <string>
  5. #include "SortedList.h"
  6.  
  7. using namespace std;
  8.  
  9. void fileName();
  10.  
  11. void main(){
  12.  
  13.     fileName();
  14.  
  15.     /*string order;
  16.     cout<<"Enter 'A' for ascending or 'D' for descending ";
  17.     cin>>order;
  18.  
  19.     if(order == 'D'){
  20.         SortedList list("descending");
  21.     }
  22.     else
  23.         SortedList list("ascending");*/
  24.  
  25.     cin.clear();
  26.  
  27.     SortedList list("ascending");
  28.  
  29.     list.appendNode(23);
  30.  
  31.     list.printList();
  32. }
  33.  
  34. void fileName(){
  35.  
  36.     ifstream infile;
  37.  
  38.     cout<<"Please enter a name for your file: ";
  39.     string x;
  40.     getline(cin,x);
  41.  
  42.     if(x == "\0"){
  43.         cout<<"Your filename will be nums.in";
  44.         infile.open("nums.in");
  45.     }
  46.     else{
  47.         cout<<"Your filename will be "<<x.c_str()<<endl<<endl;
  48.         infile.open(x.c_str());
  49.     }    
  50. }
Expand|Select|Wrap|Line Numbers
  1. // SortedList.cpp: implementation of the SortedList class.
  2. //
  3. //////////////////////////////////////////////////////////////////////
  4.  
  5. #include <iostream>
  6. #include <fstream>
  7. #include <string>
  8. #include "SortedList.h"
  9.  
  10. using namespace std;
  11.  
  12. //////////////////////////////////////////////////////////////////////
  13. // Construction/Destruction
  14. //////////////////////////////////////////////////////////////////////
  15.  
  16. SortedList::SortedList(string order)
  17. {
  18.  
  19.     if(order == "descending") 
  20.         cout<<"so you want a descending list"<<endl; 
  21.     else 
  22.         cout<<"so you want an ascending list"<<endl; 
  23.     head = NULL; 
  24.  
  25. }
  26.  
  27. SortedList::~SortedList()
  28. {
  29.  
  30. }
  31.  
  32. /*void SortedList::appendNode(int inData){
  33.  
  34.     node *Ptr = head; // combining the steps; create a pointer and assign it to head
  35.                              //Ptr = head;
  36.     node *nodePtr;
  37.     nodePtr = new node;
  38.  
  39.     nodePtr->data = inData;
  40.     nodePtr->next = NULL;
  41.  
  42.     while(Ptr != NULL){
  43.         if(Ptr->next == NULL){
  44.             Ptr->next = nodePtr;
  45.  
  46.         }
  47.         else//(nodePtr->next != NULL)
  48.             Ptr = Ptr->next;
  49.     }
  50. }*/
  51.  
  52. void SortedList::appendNode(int inData){
  53.     node *Ptr; 
  54.  
  55.     node *nodePtr;             
  56.     nodePtr = new node; 
  57.     nodePtr->data=inData; 
  58.     nodePtr->next=NULL; 
  59.  
  60.     if(head==NULL) 
  61.         head = nodePtr; 
  62.     else{
  63.         Ptr= head;
  64.         while(Ptr->next!=NULL){
  65.             Ptr=Ptr->next;
  66.         }
  67.         Ptr->next=nodePtr;
  68.     }
  69.     /*else{ 
  70.         Ptr = head; 
  71.         while(Ptr->next){ 
  72.             Ptr = Ptr->next; 
  73.         } 
  74.         Ptr->next = nodePtr; 
  75.     } */
  76. }
  77.  
  78. void SortedList::insertNode(int inData){
  79.  
  80.     node *Ptr = head;
  81.     node *tempPtr = head->next;
  82.  
  83.     node *nodePtr;
  84.     nodePtr = new node;
  85.     head->next = nodePtr;
  86.     nodePtr->data = inData;
  87.     nodePtr->next = NULL;
  88.  
  89.     while(Ptr != NULL){
  90.         if(Ptr->data > tempPtr->data)
  91.         {
  92.             Ptr->next = nodePtr;
  93.             nodePtr->next = tempPtr;
  94.             tempPtr = tempPtr->next;
  95.         }
  96.         else //(Ptr->data < tempPtr->data)
  97.         {
  98.             Ptr = Ptr->next;
  99.             tempPtr = tempPtr->next;
  100.         }
  101.     }
  102. }
  103.  
  104. void SortedList::printList(){
  105.     node *Ptr;
  106.     node *nodePtr;
  107.     Ptr=head;
  108.     nodePtr = head;
  109.     while(nodePtr!=NULL){
  110.         cout<<nodePtr->data<<endl;
  111.         nodePtr = nodePtr->next;
  112.     }
  113. }
  114.  
  115. void SortedList::revprintList(){
  116.  
  117. }
  118.  
  119. void SortedList::graphvizOut(){
  120.  
  121. }
  122.  
  123. /*void IntList::AppendNode(int data) 
  124.  
  125.     node *Temp; 
  126.  
  127.     node *NewNodePtr;             
  128.     NewNodePtr = new node; 
  129.     NewNodePtr->data=data; 
  130.     NewNodePtr->next=NULL; 
  131.  
  132.     if(head==NULL) 
  133.         head = NewNodePtr; 
  134.     else{ 
  135.         Temp = head; 
  136.         while(Temp->next){ 
  137.             Temp = Temp->next; 
  138.         } 
  139.         Temp->next = NewNodePtr; 
  140.     } 
  141. }*/
  142.  
Expand|Select|Wrap|Line Numbers
  1. // SortedList.h: interface for the SortedList class.
  2. //
  3. //////////////////////////////////////////////////////////////////////
  4.  
  5. #include <iostream>
  6. #include <fstream>
  7. #include <string>
  8.  
  9. using namespace std;
  10.  
  11. #if !defined(AFX_SORTEDLIST_H__960B0846_9203_4427_9B0E_F30C4B0FA28A__INCLUDED_)
  12. #define AFX_SORTEDLIST_H__960B0846_9203_4427_9B0E_F30C4B0FA28A__INCLUDED_
  13.  
  14. #if _MSC_VER > 1000
  15. #pragma once
  16. #endif // _MSC_VER > 1000
  17.  
  18. typedef int nodetype;
  19.  
  20. struct node{
  21.     nodetype data;
  22.     node*next;
  23.     node*prev;
  24. };
  25.  
  26. class SortedList  
  27. {
  28. private:
  29.     node *head;
  30. public:
  31.     SortedList(string);
  32.     ~SortedList();
  33.     void inputFile();
  34.     void appendNode(int);
  35.     void insertNode(int);
  36.     void printList();
  37.     void revprintList();
  38.     void graphvizOut();
  39.  
  40. };
  41.  
  42. #endif // !defined(AFX_SORTEDLIST_H__960B0846_9203_4427_9B0E_F30C4B0FA28A__INCLUDED_)
  43.  
Oct 9 '07 #1
19 2506
weaknessforcats
9,208 Expert Mod 8TB
I believe your design is at fault.

Since this is a linked list, your class should be appropriately named:
Expand|Select|Wrap|Line Numbers
  1. class LinkedList
  2. {
  3.  
  4. };
  5.  
  6.  
A linked list is a series Nodes connected by addresses. The Node contains the data.
Expand|Select|Wrap|Line Numbers
  1. class Node
  2. {
  3.      Datatype* the data;
  4.      Node* next;
  5.      Node* prev;
  6. };
  7.  
The LinkedList just need info on the start, end and current position (in the cas eof a traverse) of the list:
Expand|Select|Wrap|Line Numbers
  1. class LinkedList
  2. {
  3.     Node* start;
  4.     Node* end;
  5.     Node* current;
  6.  
  7. };
  8.  
The only mention of Node next/prev pointers will be in the Node member functions.

The Node class does not know there is a list. All it knows is that there are Nodes with data. That means you can write twomethods on the Node to insert the this object before or after the Node used on the call.

Expand|Select|Wrap|Line Numbers
  1. class LinkedList
  2. {
  3.     Node* start;
  4.     Node* end;
  5.     Node* current;
  6.    public:
  7.      void InsertAfter(Node* first);
  8.      void InsertBefore(Node* first);
  9.  
  10. };
  11.  
To sort the list, you just need a method on the LinkedList class
Expand|Select|Wrap|Line Numbers
  1. class LinkedList
  2. {
  3.     Node* start;
  4.     Node* end;
  5.     Node* current;
  6.  
  7.    public:
  8.      enum Sequence {ASCENDING, DESCENDING};
  9.      void Sort(enum Sequence);
  10.  
  11. };
  12.  
The Datatype for the data in the Node is a second level of development. Initially, I would just use an int until the linked list code is working. Then I would create a template class for the Datatype.
Oct 9 '07 #2
beacon
579 512MB
I believe your design is at fault.

Since this is a linked list, your class should be appropriately named:
Expand|Select|Wrap|Line Numbers
  1. class LinkedList
  2. {
  3.  
  4. };
  5.  
  6.  
A linked list is a series Nodes connected by addresses. The Node contains the data.
Expand|Select|Wrap|Line Numbers
  1. class Node
  2. {
  3.      Datatype* the data;
  4.      Node* next;
  5.      Node* prev;
  6. };
  7.  
The LinkedList just need info on the start, end and current position (in the cas eof a traverse) of the list:
Expand|Select|Wrap|Line Numbers
  1. class LinkedList
  2. {
  3.     Node* start;
  4.     Node* end;
  5.     Node* current;
  6.  
  7. };
  8.  
The only mention of Node next/prev pointers will be in the Node member functions.

The Node class does not know there is a list. All it knows is that there are Nodes with data. That means you can write twomethods on the Node to insert the this object before or after the Node used on the call.

Expand|Select|Wrap|Line Numbers
  1. class LinkedList
  2. {
  3.     Node* start;
  4.     Node* end;
  5.     Node* current;
  6.    public:
  7.      void InsertAfter(Node* first);
  8.      void InsertBefore(Node* first);
  9.  
  10. };
  11.  
To sort the list, you just need a method on the LinkedList class
Expand|Select|Wrap|Line Numbers
  1. class LinkedList
  2. {
  3.     Node* start;
  4.     Node* end;
  5.     Node* current;
  6.  
  7.    public:
  8.      enum Sequence {ASCENDING, DESCENDING};
  9.      void Sort(enum Sequence);
  10.  
  11. };
  12.  
The Datatype for the data in the Node is a second level of development. Initially, I would just use an int until the linked list code is working. Then I would create a template class for the Datatype.
I appreciate your help, but we haven't learned enum, templates, or the 'this' object yet. I'm sure that knowing these things would make my program much easier, but I'm pretty much confined to what is contained herein.
Oct 9 '07 #3
arnaudk
424 256MB
Use enums, they're very simple and make your code more readable, it'll take you two minutes to learn how they work.

enum Sequence {ASCENDING, DESCENDING};
void Sort(enum Sequence);

is just pretty way of saying

int Sequence;
void Sort (int Sequence);

where you decide that Sequence=0 means ascending, Sequence=1 means descending.

You don't need to use templates at this stage if you don't want to. Just replace DataType by int or whatever, or you can typedef DataType as an alias to some other type. You can implement the suggestions above without using the this pointer.

Finally, there's no point in quoting the entire previous message in your answer, is there?
Oct 10 '07 #4
weaknessforcats
9,208 Expert Mod 8TB
I appreciate your help, but we haven't learned enum, templates, or the 'this' object yet. I'm sure that knowing these things would make my program much easier, but I'm pretty much confined to what is contained herein.
I can understand not knowing templates.

However, enums are prehistoric C and you should know those by now.

But you can't use classes and write member functions without knowing what the this pointer is. The this pointer always contains the address of the object that contains the member data that the member function uses.
Oct 10 '07 #5
beacon
579 512MB
Sorry about the quote...it automatically came up like that when I hit reply and I wasn't paying attention. I'm going to read over your suggestions and try them out again. I'll post again if I stumble across something else confusing.\

Thanks...
Oct 25 '07 #6
beacon
579 512MB
I can understand not knowing templates.

However, enums are prehistoric C and you should know those by now.

But you can't use classes and write member functions without knowing what the this pointer is. The this pointer always contains the address of the object that contains the member data that the member function uses.
I wish you'd tell that to my professor. I hadn't programmed in any language but HTML before taking this class. I took a first level computer science class last semester, but we didn't cover anything like this then either. We've only focused on C++...no C whatsoever besides the fact that you can use using namespace std to avoid having to type std::cout or what have you.

Those are just a couple of reasons why I'm so frustrated with computer science at the moment. I love working with computers, but I feel like my professors aren't covering things that should be covered after speaking with people that have been in the game for a while.

Thanks for getting on to me by the way considering that you didn't even offer a lick of helpful advice this time around. What the hell is this forum for if users, nay moderators, like you are going to degrade other people that are trying to and are eager to learn a language. Instead of teaching me, you belittle me. That's not very becoming of someone that claims they've taught C++ for 15 years. Just because you've had more training and time spent with this doesn't mean that you are better than me. Why don't you go find a meat bathing suit and take your happy ass swimming with some sharks?
Oct 25 '07 #7
Studlyami
464 Expert 256MB
I think you misinterpreted the intention of that post I didn't see it as a personal attack, but a person who is just surprised that you didn't know some of the more basic topics before you were taking on a couple more of the complex ones and from the sound of it, the class structure at your school didn't cover what was needed.

As for not offering help he helped you on your design and he gave you several reference points in which you could expand your knowledge and help the program at hand (looking up enums for example). This site is one of the few sites where people here will actually help you with your program and understand what it is doing rather than just giving out an answer.
Oct 26 '07 #8
beacon
579 512MB
I think you misinterpreted the intention of that post I didn't see it as a personal attack, but a person who is just surprised that you didn't know some of the more basic topics before you were taking on a couple more of the complex ones and from the sound of it, the class structure at your school didn't cover what was needed.

As for not offering help he helped you on your design and he gave you several reference points in which you could expand your knowledge and help the program at hand (looking up enums for example). This site is one of the few sites where people here will actually help you with your program and understand what it is doing rather than just giving out an answer.
True, he did help me previously and I'm not knocking that, but my response was to his last post. Besides, if he was surprised that I hadn't learned those things it still baffles me why he would harp on it and not try to figure out why we hadn't covered those items in class.

Additionally, he assumed that I had experience in C, which is not the case and probably the thing that bothered me the most. I actually agreed with him that I should have learned those things by now, but for some reason my professor haven't felt like they were important pieces of the curriculum.

I absolutely love this forum and all of the help I've received. Plus, I enjoy being able to help other people with any problems they might have when I have the knowledge to do so.

Anyway, I apologize to weakness for the whole meat bathing suit crack. It was out of line, but I would like to request that everyone be careful about the response they give because they can very easily be misconstrued, as was the case in this instance if he, in fact, had good intentions. This is especially true with users, like myself, who are just starting out. I'd like to believe that no one on any of these forums would like to be the reason that an individual lost interest in programming altogether.
Oct 26 '07 #9
weaknessforcats
9,208 Expert Mod 8TB
To beacon:

No need to apologize.

One of my first instructors told me that C++ cannot be learned until you weep the necessary tears. He explained that the necessary tears occur late, late at night after you have been working on one problem for hours and finally, you slam you keyboard into your monitor, with tears in your eyes shouting: "Why won't this &^(^$* thing compile!!!". At that point, he said, you will reach the "teachable moment" and in that moment you will learn.

Stick with me, beacon, we have all been in your position and have great empathy for you.
Oct 28 '07 #10
beacon
579 512MB
Well, I had to put this program on hold to work on some other things, which probably wasn't the best thing to do, but I'm back and I think I have a better understanding of what I need to do.

Problem now is something basic, I'm sure, but still presenting problems for me. Here's the gist:

Forget linked lists for a minute. I have created a file with random numbers in it (called "nums.in") using a function. I need to get these random numbers in sorted order, either ascending or descending.

I'm guessing that I need to read in the numbers from the file I created, compare them, and write them out to either the same file or a different file. I can read in numbers okay (using a while(!infile.eof())), but how do I compare the number being read in with the number that is at the end/beginning of the list (depending on if ascending or descending is chosen)?

Would I do something like this (for ascending):
Expand|Select|Wrap|Line Numbers
  1. infile>>x;
  2. while(!infile.eof()){
  3.      infile>>y;
  4.      if(x>y){
  5.           ofile<<x<<endl;
  6.           ofile<<y<<endl;
  7.      }
  8.      else{
  9.           ofile<<y<<endl;
  10.           ofile<<x<<endl;
  11.      }   
  12. }
  13.  
Once the numbers are in order, then I can begin appending, inserting, and printing my list, right? Do these numbers from the file get infiled into their own node?

Thanks for the help,
B
Nov 10 '07 #11
weaknessforcats
9,208 Expert Mod 8TB
I suggest you keep your list in sorted order to begin with.

So you create an emty list.
You read a number from the file.
You add it to the list.
Repeat the previous step until the end of file is reached.

You now have a sorted list.

That's about all the code in main().

Now the add function:
1) starts at the Node address passed in
2) compares the number to the number in the node.
3) if the number is less than the node:
a) create a new node with the number in it.
b) insert the new node after the previous node.
Otherwise, you advance to the next node in the list
4) Repeat step 2 and 3.
Nov 10 '07 #12
beacon
579 512MB
So, I created the list of "random" numbers and sent it to an outfile. Now I need to turn around and read in the numbers into sorted order, right? Do I need to place these numbers in a different file if I want to track or check the output?

I'm not sure I know how to read in a number, then read in another number and compare it to the last number that I read in.
Nov 10 '07 #13
Ganon11
3,652 Expert 2GB
I would focus on reading all the numbers into an array first, and then sorting the array. There are a few sorting methods outlined in the C++ Articles section that are very simple to code (but not efficient. For your program, though, this shouldn't matter.). If you need something faster (but more difficult to code), try Quick Sort.
Nov 10 '07 #14
beacon
579 512MB
Hey Ganon,

That seems like extra work. It would seem to me that I could read in a number, compare it to the previous number, and then place it before or after that number. As each number is read in, there should be only one comparison made to sort the list.

I was hoping to read in the random numbers into sorted order so I don't have to sort them later. This will make using my class methods easier to implement.

I could be wrong, but wouldn't using an array take up more memory, especially if I try to sort it?
Nov 10 '07 #15
Ganon11
3,652 Expert 2GB
If you're only making one comparison per number, you won't get it into sorted order. And how would you print it before if you are outputting to a file? You may be interested in Insertion Sort, but you'll still need to get the numbers into an array before sorting.

Basically, if you're looking at only 2 numbers at a time, you can properly sort those 2 numbers, but that doesn't mean the entire list of numbers will be sorted. Take the following number sequence as an example:

1, 3, 8, 4, 6, 5, 2

So you read 1 and 3 in. 1 is less than 3, so you print that. Then you grab 8. 3 is less than 8, so you print 3. Now you get 4. 4 is less than 8, so you print that, etc, etc. The final list you get is:

1, 3, 4, 6, 5, 2, 8

which is obviously not sorted.
Nov 10 '07 #16
beacon
579 512MB
Ahh, I see. I don't know why I thought I could compare them that way. I guess I will need some kind of sort, regardless.
Nov 11 '07 #17
weaknessforcats
9,208 Expert Mod 8TB
Now the add function:
1) starts at the Node address passed in
2) compares the number to the number in the node.
3) if the number is less than the node:
a) create a new node with the number in it.
b) insert the new node after the previous node.
Otherwise, you advance to the next node in the list
4) Repeat step 2 and 3.
1, 3, 8, 4, 6, 5, 2


So create an empty list, then follow the steps I outlined:
1) pass in 1
-list is empty
- Node 1 = 1
2) pass in 3
- 3 not less than 1
-advance list
-you are at the end
- add 3 as ne end of list
- Node 1 = 1, Node 2 = 3
3)pass in 8
-advance until 8 is less than the node
-you are at the end
- add 8 as new end of list
- Node 1 = 1, Node 2 = 3, Node 3 = 8
4)pass in 4
-advance until 4 is less than node.
- insert 4 after Node 2
- Node 1 = 1, Node 2 = 3, Node 3 = 4, Node 4 = 8
5)pass in 6
-advance until 6 is less than node.
- insert 6 after Node 3
- Node 1 = 1, Node 2 = 3, Node 3 = 4, Node 4 = 6, Node 5 = 8
6)pass in 5
-advance until 5 is less than node.
- insert 5 after Node 3
- Node 1 = 1, Node 2 = 3, Node 3 = 4, Node 4 = 5, Node 5 = 6, Node 6 = 8
7)pass in 2
-advance until 2 is less than node.
- insert 2 after Node 1
- Node 1 = 1, Node 2 = 2, Node 3 = 3, Node 4 = 4, Node 5 = 6, Node 6 = 8

You don't need either an array or a sort.
Nov 11 '07 #18
beacon
579 512MB
I'm confused still, but what's new. So basically I should use my insert node method to sort the data (I know the names of my methods don't coincide with my intentions, but they are the names my professor asked us to use)? Here's my updated code. Any thoughts??

Expand|Select|Wrap|Line Numbers
  1. void SortedList::InsertNode(int data)  
  2.  
  3. {
  4.     node * temp;   
  5.     node * nodeptr;   
  6.     node * nodeptrprev; 
  7.     temp = new node;    
  8.     temp->data=data;    
  9.     temp->next=NULL;   
  10.  
  11.     if(!descending)        
  12.     {
  13.        if (head == NULL)    
  14.        {                    
  15.            head = temp;   
  16.            return;            
  17.        }
  18.        nodeptr = head;    
  19.        nodeptrprev = nodeptr;    
  20.  
  21.        while(nodeptr->data < temp->data && nodeptr->next != NULL)
  22.        {        
  23.             nodeptrprev = nodeptr;    
  24.             nodeptr = nodeptr->next; 
  25.        }            
  26.  
  27.        if(nodeptr->next == NULL && nodeptr->data < temp->data)
  28.        {     
  29.              nodeptr->next=temp; 
  30.        }        
  31.        else
  32.        {
  33.     if (nodeptrprev == head && nodeptrprev->data > temp->data)
  34.     {        
  35.          head = temp;    
  36.                      temp->next = nodeptrprev;
  37.     }
  38.     else
  39.     {
  40.          temp->next = nodeptr;    
  41.                      nodeptrprev->next = temp;
  42.     }
  43.        }
  44.     }
  45.     else   
  46.     {
  47.         if (head == NULL) 
  48.         {
  49.             head = temp;   
  50.             return;        
  51.         }
  52.         nodeptr = head;   
  53.         nodeptrprev = nodeptr;  
  54.         while(nodeptr->data > temp->data && nodeptr->next != NULL)
  55.         {   
  56.             nodeptrprev = nodeptr;  
  57.             nodeptr = nodeptr->next;  
  58.         }
  59.             if(nodeptr->next == NULL && nodeptr->data > temp->data)
  60.                 {    
  61.                     nodeptr->next=temp;    
  62.                 }
  63.             else  
  64.             {    
  65.                 if (nodeptrprev == head && nodeptrprev->data < temp->data)
  66.                 {                   
  67.                     head = temp;    
  68.                     temp->next = nodeptrprev;   
  69.                 }                
  70.                 else    
  71.                 {
  72.                     temp->next = nodeptr;   
  73.                                 nodeptrprev->next = temp;    
  74.                 }        
  75.             }
  76.     }
  77. }
Nov 11 '07 #19
weaknessforcats
9,208 Expert Mod 8TB
I am going to put mkjy comments inside your code sample.

void SortedList::InsertNode(int data)

{
node * temp;
node * nodeptr;
node * nodeptrprev;
temp = new node;
temp->data=data;
temp->next=NULL;

Why not just say ascending ???
I assuke you are using an enum.
VVVVVVVVVVVV
if(!descending)
{
if (head == NULL)
{
temp is an uninitialized node*. You need to malloc a mode and put the data in it before you return.
VVVVVVVVV
head = temp;
return;
}
nodeptr = head;
if head is the start of the list then there is not previous node and
so nodeptrprev should be set to 0.
VVVVVVVVVVVVVVVVV
nodeptrprev = nodeptr;
just compare the data in the new node (temp) to the list (nodeptr).
Since this is an ascending sort stay in the loop as long as the new data is greater than the list:
while (temp->data > nodeptr->data)
{
if (nodeptrprev == 0)
{
// temp is new end of list
nodeptrprev = temp;
return
}
temp->next = nodeptrprev;
nodeptrprev = temp;
return;

So what's with all the code???
VVVVVVVVVVVVVVVVVVVVVV
while(nodeptr->data < temp->data && nodeptr->next != NULL)
{
nodeptrprev = nodeptr;
nodeptr = nodeptr->next;
}

if(nodeptr->next == NULL && nodeptr->data < temp->data)
{
nodeptr->next=temp;
}
else
{
if (nodeptrprev == head && nodeptrprev->data > temp->data)
{
head = temp;
temp->next = nodeptrprev;
}
else
{
temp->next = nodeptr;
nodeptrprev->next = temp;
}
}
}
else
{
if (head == NULL)
{
head = temp;
return;
}
nodeptr = head;
nodeptrprev = nodeptr;
while(nodeptr->data > temp->data && nodeptr->next != NULL)
{
nodeptrprev = nodeptr;
nodeptr = nodeptr->next;
}
if(nodeptr->next == NULL && nodeptr->data > temp->data)
{
nodeptr->next=temp;
}
else
{
if (nodeptrprev == head && nodeptrprev->data < temp->data)
{
head = temp;
temp->next = nodeptrprev;
}
else
{
temp->next = nodeptr;
nodeptrprev->next = temp;
}
}
}
}
You could also do the head == NULL check before you do the ascending/descending check. That would eliminate one test from the function.

Also, the ascending/descending has to do with how to compare the the two nodes based on gthe desired . That test should be inside the loop rather than outside.

The pseudocode might be:

Is list empty?? If yes, temp is new head of list ->> return.

Loop:
While list->next != NULL
if (ascending)
is new data greater than list
insert new data after previous node
return
if (descending)
is new data less that list
insert new data after previous node
return
Nov 12 '07 #20

Sign in to post your reply or Sign up for a free account.

Similar topics

10
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...
19
by: RAJASEKHAR KONDABALA | last post by:
Hi, Does anybody know what the fastest way is to "search for a value in a singly-linked list from its tail" as oposed to its head? I am talking about a non-circular singly-linked list, i.e.,...
7
by: Kieran Simkin | last post by:
Hi all, I'm having some trouble with a linked list function and was wondering if anyone could shed any light on it. Basically I have a singly-linked list which stores pid numbers of a process's...
12
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...
57
by: Xarky | last post by:
Hi, I am writing a linked list in the following way. struct list { struct list *next; char *mybuff; };
2
by: Paminu | last post by:
I have a Linked-List and would like to create pointers to elements in this list. e.g I would like two pointers that point to each of their elements in the Linked-List. But there should always be...
12
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...
9
by: william | last post by:
When implementing Linked list, stack, or trees, we always use pointers to 'link' the nodes. And every node is always defined as: struct node { type data; //data this node contains ... node *...
2
by: phiefer3 | last post by:
Ok, first of all I'm not sure if this is the correct forum for this question or not. But hopefully someone can help me or at least point me in the direction of the forum this belongs. First of...
11
by: Scott Stark | last post by:
Hello, The code below represents a singly-linked list that accepts any type of object. You can see I'm represting the Data variable a System.Object. How would I update this code to use...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
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,...
0
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...
0
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,...
0
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...
0
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...
0
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...

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.