Welcome to Dream.In.Code
Getting C++ Help is Easy!

Join 136,558 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 1,928 people online right now. Registration is fast and FREE... Join Now!




need link list help?

 
Reply to this topicStart new topic

need link list help?

shadowman187
17 May, 2008 - 05:27 PM
Post #1

New D.I.C Head
*

Joined: 1 May, 2008
Posts: 3

im working on a program that inserts 25 intergers from 0 to 100 in order,and calculates the sum of the elements.
but my program doesnt print out 25 intergers it only prints out 2 ,3 ,5 or 6 numbers. and sometimes it doesnt arrange all the numbers in order. can anyone help? this is what i have so far.
CODE

#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

class Node;

class List{
public:
    List();
    void setNode( int );
    bool isEmpty( void );
    void printList( void );

private:
    Node *firstPtr;
    Node *lastPtr;
};

class Node{
    friend class List;
public:
    Node( int );                                
    int getData( void );
private:
    int data;
    Node *nextPtr;
};

int main(){

    srand( time( 0 ) );

    List myList;

    for( int i = 1; i <= 25; i++ )
        myList.setNode(1+ rand() % 100 );
    

    myList.printList();
    cout<<endl;

    return(0);
}

List::List() : firstPtr( 0 ), lastPtr( 0 )
{
    
}

void List::setNode( int d ){

    Node *newPtr = new Node( d ); //new temp node

    Node *temp = firstPtr;
    Node *trailTemp = firstPtr;


    if( isEmpty() )
        firstPtr = newPtr;

    else if( newPtr->getData() > temp->getData() )
    {
            while( newPtr->getData() > temp->getData() && temp->nextPtr != 0 ){
        
                temp = temp->nextPtr;
                trailTemp->nextPtr = temp;
            }

            if( temp->nextPtr == 0 ){
                newPtr->nextPtr = temp->nextPtr;
                temp->nextPtr = newPtr;
            } else{
                newPtr->nextPtr = temp;    
                trailTemp->nextPtr = newPtr;
            }
    
    } else{
        newPtr->nextPtr = temp->nextPtr;
        firstPtr = newPtr;
    }
}

bool List::isEmpty() {

    return( firstPtr == 0 );
}

void List::printList( void ){
    
    Node *temp = firstPtr;

    temp = temp->nextPtr;

    while( temp->nextPtr != 0 ){            //traverse the list
        cout << temp->getData() << " ";    // print out at each node.
        temp = temp->nextPtr;
    }

    cout << temp->getData();
}

Node::Node( int d ) :  data( d ), nextPtr( 0 )
{

}

int Node::getData()
{
    return( data );
}

User is offlineProfile CardPM
+Quote Post

Reply to this topicStart new topic
Time is now: 12/2/08 11:29PM

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month