C++ School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Help with linked list sort sorta works Rate Topic: -----

#1 tootintorrey  Icon User is offline

  • New D.I.C Head
  • Pip

Reputation: 1
  • View blog
  • Posts: 46
  • Joined: 24-March 08


Dream Kudos: 0

Share |

Help with linked list sort

Posted 12 April 2009 - 12:42 PM

hey all, ive been working on this linked list for a couple weeks now and have it almost working. i dont really like how we are being taught this since were not using real pointers so its kinda difficult to follow. basically we had to set an array of reandom numbers then sort it using a linked list. i can get it to sort the first number (that is after the high and low value, which are static when the program starts). i have it printing all the extra stuff like value is less then high just to help follow where it is the errors are. any suggestions would be appreciated.
Thanks

#include<iostream>

using namespace std;
int main()
{
	int rows = 10;
	int array[rows][3];
	int i,x; 
	
	cout<< "The Random unsorted numbers are: "<<endl;
	for(i=0; i<13; i++)	  
	{
	 x=(rand() % ((40-15) +1) + 15);
	 array[i][0]=0;
	 array[i][1]=0;
	 array[i][2]=0;
	 
	 array[0][0]=3;
	 //array[1][0]=-32767;  //low
	 //array[2][0]= 32767;  //high
	 array[1][0]=10;
	 array[2][0]=99;
	 array[2][1]=1;
	 array[1][2]=2;
	 
	 array[i][0]=x;
	 cout<<array[i][0]<< " ";
	}
	cout<<endl<<endl;
	cout<<"Value	Before	After"<<endl;
	for(i=0; i<13; i++)
	{
			 cout<<"   "<<array[i][0]<<"	  "<< array[i][1]<< "	  " << array[i][2] <<endl;				   
	}
	 cout<<endl;
	 
	 for(i=3; i<=10; i++)
	{
			 if(array[i][0]>=array[1][0])
			 {
				  // follow the link, change array[][] (the look at)
				  // moves on yes, changes on no
				  int before, after;
				  if(i==3)
				  {
				   after= array[1][2];
				   before= array[2][1];
				  }
				  else
				  {
				   before = array[i][1];
				   after = array[i][2];
				  }
					 
				  if(array[i][0]>= array[1][array[i][2]]) // goes to the after column to check the next number 
				  {
					   
						cout<<"The value ("<<array[i][0]<<") is greater than low (" <<array[1][0]<<") go to [0]["<<after<<"]"<<endl;						   
						cout<<"check if " <<array[i][0]<<" is < [0][" << array[array[i][2]][0]<<"]"<<endl;
						cout<<"before = "<<before<<endl;
						cout<<"after = " << after<< endl<<endl;
						
					  
						
						if(array[i][0] <= array[after][0]) // check if less then after if no then changes
						{ 
											   
						cout<<"The value is less then 'high' value."<<endl; 
						cout<<"array[0][0] = "<<array[0][0]<<endl;						
						cout<<"before = "<< before<<endl;
						cout<<"after = "<<after<<endl<<endl; 
						
						array[i][2]=after;   // changes the 'after' col 
						array[i][1]=before; //changes the 'before' col 
						}
															  
						array[array[i][2]][array[i][1]] = array[0][0];
						array[array[i][1]][array[i][2]] = array[0][0];
						++array[0][0];
				  }					   
			 }								
	}
	
		cout<< "Value	Before	After" <<endl;
	for(i=0; i<13; i++)
	{
			 cout<<"   "<<array[i][0]<<"	  "<< array[i][1]<< "	  " << array[i][2] <<endl;				   
	}
	 cout<<endl;
	
	system("Pause");
	return 0;
}


Was This Post Helpful? 0
  • +
  • -


#2 David W  Icon User is offline

  • DIC supporter
  • Icon

Reputation: 130
  • Posts: 1,013
  • Joined: 20-September 08


Dream Kudos: 1075

Re: Help with linked list sort

Posted 13 April 2009 - 01:49 AM

You did say 'linked-list' ...

That is a quite different data structure than an array ...

If data item 'a' has Address A, data item 'b' has address B, etc ...

then the start address is ...
(the value in the pointer variable pHead is) A
and (the node at) A points to B
and (the node at) B points to C
...
and Z (i.e. the last node/element) points to a NULL terminal value.

pHead = A; // where A is the start address that was assigned by 'new'

This simple working example may help you get stated ...

#include <iostream>
using namespace std;

struct Node
{
    int data;
    Node* next;
};

// after this following typedef statement ...
// where-ever you would have had (type) Node*
// you may now more simply use (type)  pNode

typedef Node* pNode;

//Node* take_in_more( Node* pHead)
pNode take_in_more( pNode pHead )
{
    int i=0, num;
    pNode pEnd, pNew; // recall pNode is type pointer to a Node, i.e. Node*
    char prompt[] = "('x' to eXit) Enter a value for number ";

    if( pHead != NULL ) 
    {
        // set pEnd to the address of the last node in the list
        // set i to count of nodes
        for( pEnd=pHead; pEnd->next!=NULL; pEnd = pEnd->next) ++i;
        ++i;
    }

    // advance i to next count for this new number to be input ...
    while( cout << prompt << ++i << ": " && cin >> num )
    {
        pNew = new Node;
        pNew->data = num;
        pNew->next = NULL;

        if(pHead == NULL ) // pHead is set on the first pass only ...
        {
            pHead = pNew;
            pEnd = pNew;
        }
        else // append ... for all passes after the first pass ...
        {
            pEnd->next = pNew; // link to new node
            pEnd = pNew; // reset 'pEnd' to this latest new node
        }
    }
    cin.clear(); // clear cin error flags ...
    cin.sync(); // 'flush' cin stream ...
    return pHead;
}

// show all the node datas ...
// note: pStart is a local copy of the pointer ( i.e. the address) passed to it
void show_all( pNode pStart )
{
    int i=0;
    while( pStart!=NULL )
    {
        cout << "node " << ++i << " data : " << (pStart->data) << endl;
        pStart=pStart->next;
    }
}

void delete_all( pNode& pStart )
{
    pNode pCopy; // get a variable to hold a backup copy ...
    while( pStart!=NULL )
    {
        pCopy =pStart; // copy address in pStart into pCopy ...
        pStart=pStart->next; // advance to the next address ... (it may be NULL)
        delete( pCopy ); // free ... the node at this address
    }
    // Note: When done the above loop ... pStart is equal to NULL
    // So ... via 'pass by ref' ... pStart (i.e. pHead) is set to NULL
}


int main()
{
    // Node* pHead = NULL; // Note: pHead must be NULL to start
    pNode pHead = NULL; // Note: pHead must be NULL to start

    cout << "Enter some numbers ... \n\n";
    pHead = take_in_more( pHead );
    cout << "\nSo far ...\n";
    show_all( pHead );

    cout << "\nEnter some more numbers ...\n\n";
    pHead = take_in_more( pHead );
    cout << "\nWith added ...\n";
    show_all( pHead );

    delete_all( pHead );
    cout << "\nAfter delete_all ...\n";
    show_all( pHead );

    cout << "\nNow again, enter some numbers ...\n";
    pHead = take_in_more( pHead );
    cout << "\nList at present ...\n";
    show_all( pHead );
    delete_all( pHead );

    cout << "\nPress 'Enter' to exit ... " << flush;
    cin.get(); // wait for 'Enter' key to be pressed ...
}

This post has been edited by David W: 15 April 2009 - 10:19 PM

Was This Post Helpful? 0
  • +
  • -

#3 David W  Icon User is offline

  • DIC supporter
  • Icon

Reputation: 130
  • Posts: 1,013
  • Joined: 20-September 08


Dream Kudos: 1075

Re: Help with linked list sort

Posted 13 April 2009 - 02:12 AM

And ... after you've grasped the pointer style used in linked-lists ...

here is an insert-sort example that inserts each new element, as it is entered, in order, in a list ...

#include <iostream>
#include <string>
#include <cstdlib> // for atoi converting an 'alpha' C string 'to' an 'int'

using namespace std;

struct Node
{
    string name;
    int id;
    Node* next;
};

// Note: variable type pNode if for holding an address of a 'Node'
typedef Node* pNode; 


// insert each new node in the list with names in proper order
pNode insert_sorted( pNode pHead, pNode pNew )
{
    // First ... handle case where new node should be first element
    if( pHead == NULL || pNew->name < pHead->name )
    {
        // It now becomes the first element
        pNew->next = pHead; // old pHead becomes 2nd in list
        pHead = pNew; // and this new node becomes the head of the list
    }
    else // If here ... search the linked list for the right location
    {
        pNode q = pHead; // Get a working copy of pHead in q
        // Start comparing with element AFTER 'q' ... i.e. the 'next in'
        while( q->next != NULL && q->next->name <= pNew->name )
        {
            q = q->next; // Traverse the list ...
        }
        
        // Ok, insert after 'q' by relinking the pointers
        // ( Includes inserting at end position ... where q->next == NULL )
        // A->B ... first insert ... N->B
        pNew->next = q->next; // inserted Node is first linked to the 'upstream node'
        // and now A->N
        q->next = pNew;  // and 'q' is updated to link to the new node
    }

    return pHead;
}

pNode take_in_more( pNode pHead )
{
    pNode pTmp;
    string tmpStr;
    int num;
    char prompt[] = "('Enter' to exit) ... Enter name: ";
    char prompt2[] = "Enter ID number: ";

    while( cout << prompt && getline( cin, tmpStr ) )
    {
        if( tmpStr == "" ) break;
        pTmp = new Node;
        pTmp->name = tmpStr;
        cout << prompt2;
        getline( cin, tmpStr );
        pTmp->id = atoi( tmpStr.c_str() );

        // Note: the address held in pHead may be updated during the 'insert'
        pHead = insert_sorted( pHead, pTmp ); // Note: HERE we insert each Node
    }

    return pHead;
}

// show all the node data ...
// note: pStart is a local copy of the pointer ( i.e. the address) passed to it
void show_all( pNode pStart )
{
    int i = 0;
    while( pStart != NULL )
    {
        cout << "node " << ++i << " with id: " << pStart->id
             << " name : " << pStart->name << endl;
        pStart = pStart->next;
    }
}

void delete_all( pNode& pStart )
{
    pNode pCopy; // get a variable to hold a backup copy ...
    while( pStart != NULL )
    {
        pCopy = pStart; // copy address in pStart into pCopy ...
        pStart = pStart->next; // advance to the next address ... (it may be NULL)
        delete( pCopy ); // free ... the node at this address
    }
    // Note: When done the above loop ... pStart is equal to NULL
    // So ... via 'pass by ref' ... pStart (i.e. pHead) is set to NULL
}


int main()
{
    pNode pHead = NULL; // Note: pHead must be NULL to start
    
    cout << "Enter some data ... \n\n";
    pHead = take_in_more( pHead );
    cout << "\nSo far ...\n";
    show_all( pHead );
    
    cout << "\nEnter some more data ...\n\n";
    pHead = take_in_more( pHead );
    cout << "\nWith added ...\n";
    show_all( pHead );

    delete_all( pHead );
    cout << "\nAfter delete_all ...\n";
    show_all( pHead );
    
    cout << "\nNow again, enter some data ...\n";
    pHead = take_in_more( pHead );
    cout << "\nList at present ...\n";
    show_all( pHead );
    delete_all( pHead );

    cout << "\nPress 'Enter' to exit ... " << flush;
    cin.get(); // wait for 'Enter' key to be pressed ...
}


Shalom,
David
http://developers-he.../index.p...opic,127.0.html

This post has been edited by David W: 18 April 2009 - 06:20 PM

Was This Post Helpful? 1
  • +
  • -

#4 tootintorrey  Icon User is offline

  • New D.I.C Head
  • Pip

Reputation: 1
  • View blog
  • Posts: 46
  • Joined: 24-March 08


Dream Kudos: 0

Re: Help with linked list sort

Posted 13 April 2009 - 06:42 AM

alright thank you, although this is a little more advanced then what im working with i think i will be able to figure it out. like i said it doesnt make sense that we havent really learned pointers but were assigned a linked list. :crazy:
Was This Post Helpful? 0
  • +
  • -

#5 David W  Icon User is offline

  • DIC supporter
  • Icon

Reputation: 130
  • Posts: 1,013
  • Joined: 20-September 08


Dream Kudos: 1075

Re: Help with linked list sort

Posted 13 April 2009 - 04:42 PM

Pointers are just variables to hold an address ...

And ... getting the bits, at different addresses, (of various memory chunks in RAM), and interpreting that bit pattern ...

is it data? (if data ... what decoding to use?) ...
is it an instruction? (Ok ... execute that instruction) ...

is really what computing is all about.

// you can refer to a value ... directly ... by its variable name

int number = 5;
cout << number << endl; // prints 5

// or ... indirectly ... by its address ...

// Note: pNumber is declared as a variable to hold the address of an 'int'
int* pNumber = &number; // or ... int* pNumber; pNumber = &number;
cout << *pNumber << endl; // prints 5 



This re-edited program below, (with more comments), may help ...


#include <iostream>

using namespace std;

struct Node
{
    int data;
    Node* next; // Note: 'next' is used to hold the address of the 'next' Node
};

// Note: pNode is here 'defined' as a variable type to hold an address of a 'Node'
typedef Node* pNode;

// Note: pHead gets updated (in main) by 'pass by ref'
void take_in_more( pNode& pStart )
{
    int i=0, num;
    pNode pEnd, pNew;
    char prompt[] = "('x' to eXit) Enter number ";

    // if any nodes exist ...
    // set pEnd to address of the last node in the list, set i to num. of nodes
    if( pStart != NULL )
    {
        for( pEnd = pStart; pEnd->next != NULL; pEnd = pEnd->next) ++i;
        ++i;
    }

    // advance i to show num. of next new integer to be input ...
    while( cout << prompt << ++i << ": " && cin >> num )
    {
        pNew = new Node; // get new memory to hold a new 'int' and a new 'address'
        pNew->data = num; // Ok ... copy 'num' to this new memory to hold an 'int'
        pNew->next = NULL; // don't forget to 'NULL terminate' each new 'end' Node

        if(pStart == NULL ) // pHead is set ONLY if the list is empty ...
        {
            pStart = pNew; // pHead now holds this address (and is NOT NULL now)
            pEnd = pNew; // Note: 'pEnd' is set here ... for this unique case
        }
        else // append ... for all passes with a list of one or more elements
        {
            pEnd->next = pNew; // link 'end' Node to new node (after it now)
            pEnd = pNew; // reset 'pEnd' to hold address of this latest new node
        }
    }
    cin.clear(); // clear cin error flags ...
    cin.sync(); // 'flush' cin stream ...
}

// show all the node data ...
// Note: pStart is a local copy of the pointer (to hold the address) passed in
void show_all( pNode pStart )
{
    int i=0;
    for( ; pStart!=NULL; pStart=pStart->next  )
        cout << "node " << ++i << " data : " << (pStart->data) << endl;
}

void delete_all( pNode& pStart )
{
    pNode pCopy; // get a variable to hold a backup copy ...
    while( pStart!=NULL )
    {
        pCopy =pStart; // copy address in pStart into pCopy ...
        pStart=pStart->next; // advance to the next address ... (it may be NULL)
        delete( pCopy ); // free ... the node at this address
    }
    // Note: When done the above loop ... pStart is equal to NULL
    // So ... via 'pass by ref' ... pStart (i.e. pHead) is set to NULL
}



int main() ///////////////////////// BEGIN MAIN ////////////////////////////////
{
    pNode pHead = NULL; // Note: pHead must be NULL to start
    
    cout << "Enter some numbers ... \n\n";
    take_in_more( pHead );
    cout << "\nSo far ...\n";
    show_all( pHead );
    
    cout << "\nEnter some more numbers ...\n\n";
    take_in_more( pHead );
    cout << "\nWith added ...\n";
    show_all( pHead );

    delete_all( pHead );
    cout << "\nAfter delete_all ...\n";
    show_all( pHead );
    
    cout << "\nNow again, enter some numbers ...\n";
    take_in_more( pHead );
    cout << "\nList at present ...\n";
    show_all( pHead );
    delete_all( pHead );

    cout << "\nPress 'Enter' to exit ... " << flush;
    cin.get(); // wait for 'Enter' key to be pressed ...
    
} ///////////////////////////////// END MAIN ///////////////////////////////////



And ... the 'pass by ref' syntax used here may make the code a little simpler ...

#include <iostream>
#include <string>
#include <cstdlib> // for atoi converting an 'alpha' (a C string) 'to' an 'int'

using namespace std;

struct Node
{
    string name;
    int id;
    Node* next; // Note: 'next' is used to hold the address of the 'next' Node
};

// Note: pNode is 'defined' as a variable type to hold an address of a 'Node'
typedef Node* pNode; 

// insert each new node in the list with names in proper order
// Note: pStart (pFront in calling function) is updated by 'pass by ref'
void insert_sorted( pNode& pStart, pNode pNew )
{
    // First ... handle case where new node should be the first element
    if( pStart == NULL || pNew->name < pStart->name )
    {
        // It now becomes the first element
        pNew->next = pStart; // old pStart becomes 2nd in list
        pStart = pNew; // and this new node becomes the start of the list
    }
    else // If here ... search the linked list for the right location
    {
        pNode q = pStart; // Get a working copy of pStart in q
        // Start comparing with element AFTER 'q' ... i.e. the 'next in'
        while( q->next != NULL && q->next->name <= pNew->name )
        {
            q = q->next; // Traverse the list ...
        }
        
        // Ok, insert after 'q' by relinking the pointers
        // ( Includes inserting at end position ... where q->next == NULL )
        // A->B ... first insert ... N->B
        pNew->next = q->next; // inserted Node is first linked to the 'upstream node'
        // and now A->N
        q->next = pNew;  // and 'q' is updated to link to the new node
    }
}

// Note: pFront (pHead in main) is updated by 'pass by ref'
void take_in_more( pNode& pFront )
{
    pNode pNew;
    string tmpStr;
    int num;
    char prompt[] = "('Enter' to exit) ... Enter name: ";
    char prompt2[] = "Enter ID number: ";

    while( cout << prompt && getline( cin, tmpStr ) )
    {
        if( tmpStr == "" ) break;
        pNew = new Node;
        pNew->name = tmpStr;
        cout << prompt2;
        getline( cin, tmpStr );
        pNew->id = atoi( tmpStr.c_str() );

        // Note: the address held in pFront may be updated during the 'insert'
        // since we are using 'pass by ref' for 'pFront' ...
        insert_sorted( pFront, pNew ); // Note: HERE we insert each Node
    }
}

// show all the node data ...
// note: pStart is a local copy of the pointer ( i.e. the address) passed to it
void show_all( pNode pStart )
{
    int i = 0;
    while( pStart != NULL )
    {
        cout << "node " << ++i << " with id: " << pStart->id
             << " name : " << pStart->name << endl;
        pStart = pStart->next;
    }
}

// Note: pStart (pHead in main) is updated by 'pass by ref'
void delete_all( pNode& pStart )
{
    while( pStart != NULL )
    {
    pNode pCopy; // get a variable to hold a backup copy ...
        pCopy = pStart; // copy address in pStart into pCopy ...
        pStart = pStart->next; // advance to the next address ... (it may be NULL)
        delete( pCopy ); // free ... the node at this address
    }
    // Note: When done the above loop ... pStart is equal to NULL
    // So ... via 'pass by ref' ... pStart (i.e. pHead in main) is set to NULL
}


int main()
{
    pNode pHead = NULL; // Note: pHead must be NULL to start
    
    cout << "Enter some data ... \n\n";
    take_in_more( pHead );
    cout << "\nSo far ...\n";
    show_all( pHead );
    
    cout << "\nEnter some more data ...\n\n";
    take_in_more( pHead );
    cout << "\nWith added ...\n";
    show_all( pHead );

    delete_all( pHead );
    cout << "\nAfter delete_all ...\n";
    show_all( pHead );
    
    cout << "\nNow again, enter some data ...\n";
    take_in_more( pHead );
    cout << "\nList at present ...\n";
    show_all( pHead );
    delete_all( pHead );

    cout << "\nPress 'Enter' to exit ... " << flush;
    cin.get(); // wait for 'Enter' key to be pressed ...
}

This post has been edited by David W: 15 April 2009 - 10:42 PM

Was This Post Helpful? 0
  • +
  • -

#6 tootintorrey  Icon User is offline

  • New D.I.C Head
  • Pip

Reputation: 1
  • View blog
  • Posts: 46
  • Joined: 24-March 08


Dream Kudos: 0

Re: Help with linked list sort

Posted 15 April 2009 - 07:43 AM

since this is for the same program i wont start a new thread. when i try to compile this i get the error invalid conversion from *int to int. im not to sure how resolve this because i didnt think i was using a pointer value. i just want the value of i-1, i tried puttint that in place of t in the actual array[t][2] part but that gives another error as well.
i tried to follow the above program but it doesnt seem to help to much since i know the logic behind the linked list sort, just not the proper/efficient way to code it.

								   else
								   {
									int t=0;
									t=--i;
									cout<<"THE VALUE OF T  : "<<t<<endl;
									after = array[array[t]][2];
									before = array[array[t]][1];
									}


This post has been edited by tootintorrey: 15 April 2009 - 07:52 AM

Was This Post Helpful? 0
  • +
  • -

#7 David W  Icon User is offline

  • DIC supporter
  • Icon

Reputation: 130
  • Posts: 1,013
  • Joined: 20-September 08


Dream Kudos: 1075

Re: Help with linked list sort

Posted 15 April 2009 - 09:55 AM

Quote

... we had to set an array of reandom (random) numbers then sort it using a linked list ...


This request is a little odd ... since once you have loaded up your array ... it would be faster and easier to just sort them in that array (with no list needed at all.)

But if the above was your 'problem' to implement ...

1. The first part ... of storing some random numbers in an array big enough to hold all the numbers ... is no big deal.

2a. The next part of reading all those numbers into a list is no big deal either ...

2b. But ... you might as well read them into the list ... and insert then in order as you go ...

#include <iostream>
// ... any other includes

const int MAX_NUM = 100; // or whatever you need ...

struct Node
{
   int number;
   Node* next;
};

typedef Node* pNode;

// prototypes ...
void insert_in_order( pNode& pStart, int num );
// ...
// ...

int main()
{
   // ...
   
   int array[MAX_NUM];
   // get your array filled with 'MAX_NUM' random numbers

   Node* pHead = NULL;

   for( int i=0; i<MAX_NUM; ++i )
	  insert_in_order( pHead, array[i] );

   display_all( pHead );

   // finish_up
}

// finish up all function definitions ..



This post has been edited by David W: 15 April 2009 - 09:58 AM

Was This Post Helpful? 0
  • +
  • -

#8 tootintorrey  Icon User is offline

  • New D.I.C Head
  • Pip

Reputation: 1
  • View blog
  • Posts: 46
  • Joined: 24-March 08


Dream Kudos: 0

Re: Help with linked list sort

Posted 15 April 2009 - 03:02 PM

alright thanks, the only thing im unsure of is what node is. like i know the * is to point to whatevers in that variable but ive never used typedef Node* pNode; before. however i guess this is good though cuz this one program is making me learn more than ive learned all semester.


oh and david when i stated the assignment i guess i worded it poorly, i dont really need to store them into an array first i could just sort it as it makes them but for simplicity i stored it into an array so i can see the numbers and know what should be going where. since i didnt use srand the numbers arent truly random, rather a set of random numbers that appears every time.

This post has been edited by tootintorrey: 15 April 2009 - 03:06 PM

Was This Post Helpful? 0
  • +
  • -

#9 David W  Icon User is offline

  • DIC supporter
  • Icon

Reputation: 130
  • Posts: 1,013
  • Joined: 20-September 08


Dream Kudos: 1075

Re: Help with linked list sort

Posted 15 April 2009 - 09:37 PM

Programming can be fun when you 'start to see' what is going on and begin to enter into the problem solving process. The ability to, via a PC, quickly try out some well designed code for a well defined task and see it actually do what it was designed to do ... you may now understand something of the joy of a great creator. (The big historical danger here though, has been ... that we become so enamoured with our little creations that we ignore our own so much more Awesome Creator.)

The word 'Node' is somewhat arbitrary ... you could use List, MyList, MyLinkedList ... or what ever might best describe 'all that is there' ...

But the word Node ... (common practice is to put cap's on the first letter of structs or classes you define/create) ... is very commonly used because it seems to well represent that idea that ONE MORE set of data, often called a data record, or in C/C++, a struct, is being discussed. The special data item included in these node or list structs (beside any other data items) ... is a pointer to the next node (next data record) ... i.e. each record/struct ALSO has a variable to hold the address of the next link in the chain.

Array's are often implemented as (equal sized) chunks of contiguous memory ... and so the address of the next element in an array can be calculated from the address of the first element ... addressFirst +(n-1)(sizeof(each_element))

Thus the array[i] notation ... where i = 0..(n-1)

BUT ... each node in a linked list will be at the address that it was given when it was created (in C++, via the 'new' operator) ... And the next node may NOT be contiguous. So ... it CAN-NOT be calculated (from the address of the first node). Thus the address of each node must be stored in the pointer variable of the previous node ... a variable often named 'next'.

The memory address of the first node, (the first node is often called 'head' or 'front' or 'start'), must be stored in a (pointer) variable ... like 'pStart' ... so we can reach there ... to start.

And for the end node in a linked list ... the value in its pointer variable 'next' will be NULL ... to signal we have reached the end of the chain.

Before we have any data records (or nodes) ... the value in pHead is (assigned) NULL to signal that the list is empty.

Of course ... all the above is with respect only to the most primitive linked list ... a list that links in the forward direction only. There are many embellishments ... but this is the common simple place to start.

If you look over the examples here ... you may have noticed 2 styles:

pass/return by ref
and
pass by value and return a function value

and that both styles were alternately used.

Take your choice here.

If/when you get to C++ classes ... you may find the void function pass/return by ref style closer to what you need ...

when you want to update the private class data members ...
in the public member functions (that have access to all the private data as if they were global variables)

You may find that you now have all the concepts and snippets that you need to put together a suitable solution to your problem.

I applaud your approach in first attempting to get some working code for the much simpler problem of just getting some random numbers into an array of numbers and displaying them.

This post has been edited by David W: 15 April 2009 - 11:28 PM

Was This Post Helpful? 1
  • +
  • -

#10 tootintorrey  Icon User is offline

  • New D.I.C Head
  • Pip

Reputation: 1
  • View blog
  • Posts: 46
  • Joined: 24-March 08


Dream Kudos: 0

Re: Help with linked list sort

Posted 17 April 2009 - 10:23 AM

thanks again for the detail, i think im going to start mine over from scratch just because i have a lot of seemingly useless code to try and get to something that can be done simpler. as for the use of node thats basically what i was trying to with my variables named before and after, which is why i was having so much trouble locating where i am at in the list. and thank you for applauding my efforts i havent had any do so yet. i see so many people going how do you do this with no work done and its like well how do you plan on learning how to code if you cant even start a program. :rolleyes: anyways thanks again lol im sure ill end up posting again within the next week with some other dumb problem related to this sort. i really just wish we were doing material in our textbook so i could have examples and guidelines to follow but meh my brains my book i guess.
Was This Post Helpful? 0
  • +
  • -

#11 David W  Icon User is offline

  • DIC supporter
  • Icon

Reputation: 130
  • Posts: 1,013
  • Joined: 20-September 08


Dream Kudos: 1075

Re: Help with linked list sort

Posted 17 April 2009 - 10:42 AM

These days ... with the web ... who needs a class for the basics ... you can surf and find most what you need ... If you are after understanding ... and not just a quick mark ... with PC's ... and once you are even just a little past 'Hello World' ... you can code and re-code ... and try things out to your heart's content until you get it just right. A good text will also be a good ref for style and supply lots of on-line snippets to quickly try new things out ... copy/paste ... change ... try-out again ... and see what the edited code does.

You may like to see these "Beginning Computer Programming" free on-line e-text series ...

http://developers-he.../index.p...opic,127.0.html
http://developers-he.../index.p...opic,106.0.html
http://developers-he...index.php/topic,46.0.html

Shalom,
David
Was This Post Helpful? 0
  • +
  • -

#12 David W  Icon User is offline

  • DIC supporter
  • Icon

Reputation: 130
  • Posts: 1,013
  • Joined: 20-September 08


Dream Kudos: 1075

Re: Help with linked list sort

Posted 19 April 2009 - 12:43 AM

P.S. just noticed an error and thought you might like to get a little more 'clear' with C/C++ pointer syntax ...

Quote

... thanks, the only thing I'm unsure of ... is ... What is a node?

Like ... I know the '*' is to point to what ever is in that variable ...



Not really ... * is used to indicate a variable is a pointer variable

int* p; // indicates that p is a variable to hold the address of an integer



Or ... * is used to de-reference an address, i.e. to take/use the value at an address ...

*p = 7; // means to assign/copy 7 to the memory beginning at the address in the (int pointer) variable p
		   // BUT this WILL CRASH if you haven't a valid address in p of memory reserved to hold an int,
		   // as we don't yet ... here ... but see the example program snippet below for a proper way to do it.

int seven = *p; // will assign/copy into the memory reserved for the variable seven ... the value 7

int* q = NULL; // declare q as an int pointer variable and assign it the initial value NULL
q = & seven;   // will copy the address of the memory reserved for 'int seven' into q ...
					// so that q now holds a valid address and NOT NULL any more

cout << *q << endl; // will print out the value at the address in q, which is 7
cout << hex << q << endl; // will print out the hexidecimal value of the address held in the variable q
cout << hex << &q << endl; // will print out the hexidecimal value of the address OF the variable q



Try out this working program ...

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    int* p; // indicates that p is a variable to hold the address of an integer

    // get some new memory to hold an integer ... (4 bytes in many systems today)
    p = new int; // put the address of (the start byte of) that memory into p

    // Or ... * is used to de-reference an address,
    // i.e. to take/use the value at an address ...
    // here we assign/copy 7 to the address held in the (int pointer) variable p

    *p = 7;
    cout << *p << endl;

    // assign/copy into memory reserved for the variable seven ... the value 7
    int seven = *p; 

    // declare q as an int pointer variable and assign it the initial value NULL
    int* q = NULL;

    // copy the address of the memory reserved for 'int seven' into q ...
    //so that q now holds a valid address and NOT NULL any more
    q = & seven; 

    // print out the value at the address in q, which is 7
    cout << *q << endl; 

    // print out the hexidecimal value of the address held in the variable q
    cout << hex << q << endl;
    cout << hex << &seven << endl; //and the address of the memory used by seven
    
    // print out the hexidecimal value of the address OF the variables q and p
    cout << hex << &q << endl; 
    cout << hex << &p << endl;
    

    cin.get();
}
// My output from running the compiled program above was ...
/*
7
7
0x23ff70
0x23ff70
0x23ff6c
0x23ff74
*/

Was This Post Helpful? 0
  • +
  • -

#13 tootintorrey  Icon User is offline

  • New D.I.C Head
  • Pip

Reputation: 1
  • View blog
  • Posts: 46
  • Joined: 24-March 08


Dream Kudos: 0

Re: Help with linked list sort

Posted 28 April 2009 - 03:12 PM

alright i tried something a little different from scratch. this time instead of the for loop and creating the numbers first i made it so you enter it and it sorts as you go. its still a bit different then your examples but i feel this is a lot closer. its starting to get close to working however at the end it always ends by not responding and it still doesnt quit sort correctly but i figured id post an update.


#include<iostream>

using namespace std;
int main()
{
	int array[10][3];
	int i,empty,loc,val,answer;
	
	for(i=0; i<13; i++)	  
	 {
	  array[i][0]=0;
	  array[i][1]=0;
	  array[i][2]=0;
	 }
	 
	 cout<<"  Linked List "<<endl;
	 
	 array[0][0]=3;	   
	 array[1][0]= 10; //-32767;  //low
	 array[2][0]= 99; //32767;  //high
	 array[2][1]=1;
	 array[1][2]=2;
	 
	empty=array[0][0];
	loc=1;
	  
	 do
	 {		   
		  cout<<"Enter number to sort:  ";
		  cin>> val;
		  array[empty][0]=val;
	  
		  do
			{  
			   if(val>array[loc][0])
			   { 
				 /* 
				 array[empty][2]= array[loc][2]; //changes before
				 array[empty][1]= array[2][loc]; //changes after
				 array[loc][2]=empty;
				 array[2][loc]=empty;
				 */
				 loc=array[loc][2];  //changes loc to next "after"
			
				 }
			else
			{ //if no
			  array[empty][2]=loc;
			  array[empty][1]=array[loc][1];
			  array[empty][1]=empty;
			  array[loc][1]=empty;
	 
			  empty++;
			 }
		  }
			  while(answer=0);	/*idk why i put answer=0 i should create a new variable called flag i realized  this is prob whats crashing it after i pasted it in here*/ 
			  
				   cout<<"Value	Before	After"<<endl;
				   for(i=0; i<13; i++)
							{
							 cout<<"   "<<array[i][0]<<"	  "<< array[i][1]<< "	  " << array[i][2] <<endl;				   
							 }
	
			  cout<<"Do you want to enter another number? (1 no)(2 yes)  ";
			  cin>> answer;
		  }		  
			  while ((answer!=1) && (answer=2));
	system("Pause");
	return 0;
}


This post has been edited by tootintorrey: 28 April 2009 - 03:17 PM

Was This Post Helpful? 0
  • +
  • -



Fast Reply

  

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users