CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Oct 2011
    Location
    Tennessee
    Posts
    46

    Question Linked List Problem

    Hey I was wondering if this is a proper way of looking through the list to find the node with the smallest data, and then deleting it. This is what I have so far there is no main to test so please excuse that. Thanks.

    These are the parts actually about finding the smallest and deleting it.
    Code:
    template <class Type>
    linkedListType<Type>::searchSmallest(const Type& smallest) const
    {
    	nodeType<Type> *current; //pointer to traverse the list
    
    	current = first; //start search at the first node
    	int smallest = current->info; // set the item to be compared
    
    	while (current != NULL && !found)
    	{
    		if (current->info < smallest)
    			smallest = current->info;
    		current = current->link;
    	}
    	return smallest;
    }
    template <class Type>
    void linkedListType<Type>::deleteSmallest(const Type& smallest)
    {	
    	delete smallest;
    }
    and here is the entire code so far.
    Code:
    #ifndef H_LinkedListType
    #define H_LinkedListType
    
    #include <iostream>
    #include <cassert>
    
    using namespace std;
    
    //Definition of the node
    
    template <class Type>
    struct nodeType
    {
    	Type info;
    	nodeType<Type> *link;
    };
    
    //***********************************************************
    // Author: D.S. Malik
    //
    // This class specifies the members to implement an iterator
    // to a linked list.
    //***********************************************************
    
    template <class Type>
    class linkedListIterator
    {
    public:
        linkedListIterator();
          //Default constructor
          //Postcondition: current = NULL;
    
        linkedListIterator(nodeType<Type> *ptr);
          //Constructor with a parameter.
          //Postcondition: current = ptr;
    
        Type operator*();
          //Function to overload the dereferencing operator *.
          //Postcondition: Returns the info contained in the node.
    
        linkedListIterator<Type> operator++();    
          //Overload the preincrement operator.
          //Postcondition: The iterator is advanced to the next node.
    
        bool operator==(const linkedListIterator<Type>& right) const;
          //Overload the equality operator.
          //Postcondition: Returns true if this iterator is equal to 
          //    the iterator specified by right, otherwise it returns
          //    false.
    
        bool operator!=(const linkedListIterator<Type>& right) const;
          //Overload the not equal to operator.
          //Postcondition: Returns true if this iterator is not equal to
          //    the iterator specified by right, otherwise it returns
          //    false.
    
    private:
        nodeType<Type> *current; //pointer to point to the current
                                 //node in the linked list
    };
    
    
    template <class Type>
    linkedListIterator<Type>::linkedListIterator()
    {
        current = NULL;
    }
    
    template <class Type>
    linkedListIterator<Type>::
                      linkedListIterator(nodeType<Type> *ptr)
    {
        current = ptr;
    }
    
    template <class Type>
    Type linkedListIterator<Type>::operator*()
    {
        return current->info;
    }
    
    template <class Type>
    linkedListIterator<Type> linkedListIterator<Type>::operator++()   
    {
        current = current->link;
    
        return *this;
    }
    
    template <class Type>
    bool linkedListIterator<Type>::operator==
                   (const linkedListIterator<Type>& right) const
    {
        return (current == right.current);
    }
    
    template <class Type>
    bool linkedListIterator<Type>::operator!=
                     (const linkedListIterator<Type>& right) const
    {   return (current != right.current);
    }
    
    
    //***********************************************************
    // This class specifies the members to implement the basic
    // properties of a linked list. This is an abstract class.
    // We cannot instantiate an object of this class.
    //***********************************************************
    
    template <class Type>
    class linkedListType
    {
    public:
        const linkedListType<Type>& operator=
                             (const linkedListType<Type>&);
          //Overload the assignment operator.
    
        void initializeList(); 
          //Initialize the list to an empty state.
          //Postcondition: first = NULL, last = NULL, count = 0;
    
        bool isEmptyList() const;
          //Function to determine whether the list is empty. 
          //Postcondition: Returns true if the list is empty, otherwise
          //    it returns false.
    
    	int searchSmallest(const Type& smallest) const;
    
    	void deleteSmallest(const Type& smallest);
    
    	int searchAllLike(const Type& searchItem) const;
    
        void print() const;
          //Function to output the data contained in each node.
          //Postcondition: none
    
        int length() const;
          //Function to return the number of nodes in the list.
          //Postcondition: The value of count is returned.
    
        void destroyList();
          //Function to delete all the nodes from the list.
          //Postcondition: first = NULL, last = NULL, count = 0;
    
        Type front() const; 
          //Function to return the first element of the list.
          //Precondition: The list must exist and must not be empty.
          //Postcondition: If the list is empty, the program terminates;
          //    otherwise, the first element of the list is returned.
    
        Type back() const; 
          //Function to return the last element of the list.
          //Precondition: The list must exist and must not be empty.
          //Postcondition: If the list is empty, the program
          //               terminates; otherwise, the last  
          //               element of the list is returned.
    
        virtual bool search(const Type& searchItem) const = 0;
          //Function to determine whether searchItem is in the list.
          //Postcondition: Returns true if searchItem is in the list,
          //    otherwise the value false is returned.
    
        virtual void insertFirst(const Type& newItem) = 0;
          //Function to insert newItem at the beginning of the list.
          //Postcondition: first points to the new list, newItem is
          //    inserted at the beginning of the list, last points to
          //    the last node in the list, and count is incremented by
          //    1.
    
        virtual void insertLast(const Type& newItem) = 0;
          //Function to insert newItem at the end of the list.
          //Postcondition: first points to the new list, newItem is
          //    inserted at the end of the list, last points to the
          //    last node in the list, and count is incremented by 1.
    
        virtual void deleteNode(const Type& deleteItem) = 0;
          //Function to delete deleteItem from the list.
          //Postcondition: If found, the node containing deleteItem is
          //    deleted from the list. first points to the first node,
          //    last points to the last node of the updated list, and
          //    count is decremented by 1.
    
        linkedListIterator<Type> begin();
          //Function to return an iterator at the beginning of the 
          //linked list.
          //Postcondition: Returns an iterator such that current is set
          //    to first.
    
        linkedListIterator<Type> end();
          //Function to return an iterator one element past the 
          //last element of the linked list. 
          //Postcondition: Returns an iterator such that current is set
          //    to NULL.
    
        linkedListType(); 
          //default constructor
          //Initializes the list to an empty state.
          //Postcondition: first = NULL, last = NULL, count = 0; 
    
        linkedListType(const linkedListType<Type>& otherList); 
          //copy constructor
    
        ~linkedListType();   
          //destructor
          //Deletes all the nodes from the list.
          //Postcondition: The list object is destroyed. 
    
    public:
        int count; //variable to store the number of list elements
                     // 
        nodeType<Type> *first; //pointer to the first node of the list
        nodeType<Type> *last;  //pointer to the last node of the list
    
    private: 
        void copyList(const linkedListType<Type>& otherList); 
          //Function to make a copy of otherList.
          //Postcondition: A copy of otherList is created and assigned
          //    to this list.
    }; 
    
    template <class Type>
    bool linkedListType<Type>::isEmptyList() const
    {
        return (first == NULL);
    }
    template <class Type>
    linkedListType<Type>::searchSmallest(const Type& smallest) const
    {
    	nodeType<Type> *current; //pointer to traverse the list
    
    	current = first; //start search at the first node
    	int smallest = current->info; // set the item to be compared
    
    	while (current != NULL && !found)
    	{
    		if (current->info < smallest)
    			smallest = current->info;
    		current = current->link;
    	}
    	return smallest;
    }
    template <class Type>
    void linkedListType<Type>::deleteSmallest(const Type& smallest)
    {	
    	delete smallest;
    }
    template <class Type>
    int linkedListType<Type>::searchAllLike(const Type& searchItem) const
    {
    	
    }
    /*
    	nodeType<Type> *current;
    	nodeType<Type> *trailCurrent;
    	bool found;
    
    	found = false;
    	trailCurrent = first;
    
    	current = first->link;
    	while(current != NULL && !found)
    	{
    		if(current->info != deleteItem)
    		{
    			trailCurrent = current;
    			current = current->link;
    		}
    		else
    			found = true;
    	}
    	if(found)
    	{
    		trailCurrent->link = current->link;
    		count--;
    
    		if(last == current)
    			last = trailCurrent;
    		delete current;
    	}
    	else
    		cout << "The item to be deleted is not in the list." << endl;
    }*/
    
    template <class Type>
    linkedListType<Type>::linkedListType() //default constructor
    {
        first = NULL;
        last = NULL;
        count = 0;
    }
    
    template <class Type>
    void linkedListType<Type>::destroyList()
    {
        nodeType<Type> *temp;   //pointer to deallocate the memory
                                //occupied by the node
        while (first != NULL)   //while there are nodes in the list
        {
            temp = first;        //set temp to the current node
            first = first->link; //advance first to the next node
            delete temp;   //deallocate the memory occupied by temp
        }
    
        last = NULL; //initialize last to NULL; first has already
                     //been set to NULL by the while loop
        count = 0;
    }
    
    template <class Type>
    void linkedListType<Type>::initializeList()
    {
    	destroyList(); //if the list has any nodes, delete them
    }
    
    template <class Type>
    void linkedListType<Type>::print() const
    {
        nodeType<Type> *current; //pointer to traverse the list
    
        current = first;    //set current so that it points to 
                            //the first node
        while (current != NULL) //while more data to print
        {
            cout << current->info << " ";
            current = current->link;
        }
    }//end print
    
    template <class Type>
    int linkedListType<Type>::length() const
    {
        return count;
    }  //end length
    
    template <class Type>
    Type linkedListType<Type>::front() const
    {   
        assert(first != NULL);
    
        return first->info; //return the info of the first node	
    }//end front
    
    template <class Type>
    Type linkedListType<Type>::back() const
    {   
        assert(last != NULL);
    
        return last->info; //return the info of the last node	
    }//end back
    
    template <class Type>
    linkedListIterator<Type> linkedListType<Type>::begin()
    {
        linkedListIterator<Type> temp(first);
    
        return temp;
    }
    
    template <class Type>
    linkedListIterator<Type> linkedListType<Type>::end()
    {
        linkedListIterator<Type> temp(NULL);
    
        return temp;
    }
    
    template <class Type>
    void linkedListType<Type>::copyList
                       (const linkedListType<Type>& otherList) 
    {
        nodeType<Type> *newNode; //pointer to create a node
        nodeType<Type> *current; //pointer to traverse the list
    
        if (first != NULL) //if the list is nonempty, make it empty
           destroyList();
    
        if (otherList.first == NULL) //otherList is empty
        {
            first = NULL;
            last = NULL;
            count = 0;
        }
        else
        {
            current = otherList.first; //current points to the 
                                       //list to be copied
            count = otherList.count;
    
                //copy the first node
            first = new nodeType<Type>;  //create the node
    
            first->info = current->info; //copy the info
            first->link = NULL;        //set the link field of 
                                       //the node to NULL
            last = first;              //make last point to the
                                       //first node
            current = current->link;     //make current point to
                                         //the next node
    
               //copy the remaining list
            while (current != NULL)
            {
                newNode = new nodeType<Type>;  //create a node
                newNode->info = current->info; //copy the info
                newNode->link = NULL;       //set the link of 
                                            //newNode to NULL
                last->link = newNode;  //attach newNode after last
                last = newNode;        //make last point to
                                       //the actual last node
                current = current->link;   //make current point 
                                           //to the next node
            }//end while
        }//end else
    }//end copyList
    
    template <class Type>
    linkedListType<Type>::~linkedListType() //destructor
    {
       destroyList();
    }//end destructor
    
    template <class Type>
    linkedListType<Type>::linkedListType
                          (const linkedListType<Type>& otherList)
    {
       	first = NULL;
        copyList(otherList);
    }//end copy constructor
    
             //overload the assignment operator
    template <class Type>
    const linkedListType<Type>& linkedListType<Type>::operator=
                          (const linkedListType<Type>& otherList)
    { 
        if (this != &otherList) //avoid self-copy
        {
            copyList(otherList);
        }//end else
    
         return *this; 
    }
    
    #endif
    Sorry that its long.
    Thanks all.

  2. #2
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Linked List Problem

    Removing a node from a linked list is a bit more complicated than just deleting it. Also, if you are going to write a function to delete an arbitrary node, you don't need to call it deleteSmallest----just deleteItem or something.

    Your searchSmallest function does not have a return type. What is it passing back out? While the actual smallest bit of data is perhaps useful, it doesn't help you during the deletion process.

  3. #3
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Location
    Florida
    Posts
    12,635

    Re: Linked List Problem

    Why is there no main to test it. If any of us were doing it, the first thing we would do is call the function and step through it in the debugger to see if it was doing what we wanted it to.

  4. #4
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Linked List Problem

    Quote Originally Posted by Wh1t3gh0st View Post
    This is what I have so far there is no main to test so please excuse that.
    Why not just write a simple main() and test the program before asking if the program is OK?

    When you develop a program, you're supposed to test individual pieces during the development. If a certain part of the progra doesn't work, you can fix it instead of waiting until the end, not knowing if what you have works or not.

    I can tell you one thing -- your copyList is too complex. You have functions to insert into a list, and a function to get an item from a list. So why is copyList so complex, given that you have these functions, and you don't reuse them?

    Here is the pseudo-code for a very easy "copyList" function, given you have the insertion and get. Assume that list2 is being copied to list1:
    Code:
    1) Remove all nodes from list1
    2) Start from beginning of list2
    3) For each data item x in list 2
            Get data x from list 2
            Insert data x in list 1
            Go to next item in list 2 
        End For
    In other words, you empty the list you want to copy to, and just insert into this list all of the data from the other list in a loop by calling insert.

    That's it. You have a function to remove all nodes from a list. You have a function that gets data from a list. You have a function that inserts into a list. You have implemented "iterators" begin and end, so you can loop very easily on all the items in list 2.

    Basically, a 5 or 6 line function, not gobs of code with pointers all over the place.
    Code:
    // destroy list 1 data -- there should be no need to check if it's empty or not, just destroy it.
    list1.destroyList();
    
    // Now list 1 is empty
    
    // point to beginning of list 2
    linkedListIterator<whatever> list2It = list2.begin();
    
    // loop for all items in list 2 until the end of list 2
    while (list2It != list2.end() )
    {
        // insert the current list 2 item at the back of list 1.  
        // It should not matter if list1 is empty at the beginning of the loop,
        // insertLast should still work
    
         list1.insertLast( *list2It );
    
       // go to next item in list 2
         ++list2It;
    }
    That is the entire (almost C++) code to copy a list to another list, given your class. Compare that with the monstrosity you have implemented now.

    Regards,

    Paul McKenzie
    Last edited by Paul McKenzie; March 2nd, 2012 at 07:27 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured