How do I go about making a ordered linked list using classes?

Hello friends :D!
I need to make a singly linked list that puts items in order based on their 'position' value. It takes the 'position' values from the command line. This is what I have thus far:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <cstdio>
using namespace std;

class MyClass{
public: MyClass(int x);
protected: int position;
MyClass *next;
}; //closing brace of MyClass

MyClass* head_ptr = NULL;

int main(int argc. char* argv[])
{
       int i = 1;

       for(i; i < argc; i++)
       {

              MyClass(atoi(argv[i]));

       } //closing brace of for loop
} //closing brace of main

MyClass::MyClass(int x)
{
        /* I'm not sure what to put in here to make the linked list ordered*/



} // closing brace of MyClass constructor 



Can you help a brother out? D:

I've made linked lists before but I have no idea how to insert a new node into the middle or end of the list (at least not in C++, the last time I did this it was using 'struct')
Last edited on
Create two new nodes, 'cur' and 'prev' and assign cur to the head of the list and pre to NULL. cur is traveling pointer, and prev follows behind it.

1
2
cur = head;
prev = NULL;


cur will be the pointer traversing the list, keeping track of where you are.
While you're not at the end of the list, and while your new item is larger than cur, increment cur and prev.
1
2
3
4
5
while (NULL!= cur && cur->item < newNode->item)
   {
      prev = cur;
      cur = cur->next;
   }


Now that you're at the node you want to be at, i.e. what cur points to, if prev is still NULL, then you haven't moved anywhere, and the new item needs to be inserted at the beginning of the list.

1
2
3
4
if (NULL == prev)
   {
      head = newNode;
   }


Else, change what prev points to so that it points to the new item.

1
2
3
4
5
else
   {
      prev->next = newNode;
      newNode->next = cur;
   }
Last edited on
Topic archived. No new replies allowed.