Linked Unsorted List

  • List implemented with linked node structure rather than arrays.

Implementation code

 

#include  “ItemType.h” 		//  unsorted.h	
    .  .  .
template <class ItemType>
class  UnsortedType
{						
public : 		      //  LINKED LIST IMPLEMENTATION
	UnsortedType ( ) ;
	~UnsortedType ( ) ;
	void   MakeEmpty ( ) ;
	bool   IsFull ( )  const ;              
	int	   LengthIs ( )  const ;                
	void   RetrieveItem ( ItemType&  item, bool&  found ) ;
	void   InsertItem ( ItemType  item ) ; 	
	void   DeleteItem ( ItemType  item ) ; 	
	void   ResetList ( );
	void   GetNextItem ( ItemType&  item ) ; 	 
private :		
	NodeType<ItemType>*  listData;
	int     length;
	NodeType<ItemType>*  currentPos;
} ;	



#include “itemtype.h”

template <class ItemType> 
UnsortedType<Itemtype>::UnsortedType ( )       // constructor
//  Pre: None.
// Post: List is empty.
{    
	length  =  0 ;
	listData = NULL;
}

template <class ItemType>
int  UnsortedType<Itemtype>::LengthIs (  )  const
// Post:  Function value = number of items in the list.
{
	return  length;
}

template <class ItemType> 
void  UnsortedType<ItemType>::RetrieveItem( ItemType&  item, bool&  found )  
//  Pre: Key member of item is initialized.
// Post: If found, item’s key matches an element’s key in the list 
//	and a copy of that element has been stored in item; otherwise,
// item is unchanged.
{  bool  moreToSearch ;
	NodeType<ItemType>*  location ;
   location = listData ;
	found = false ;
	moreToSearch = ( location  !=  NULL ) ;
	while ( moreToSearch  &&  !found ) 
	{  if ( item  == location->info )            // match here
      {  found = true ;
		  item  = location->info ;
	   }
	   else				         // advance pointer 
	   {  location = location->next ;
		 moreToSearch = ( location  !=  NULL ) ;
      }   
  }     
}
template <class ItemType> 
void UnsortedType<Itemtype>::InsertItem ( ItemType  item ) 
//  Pre: list is not full and item is not in list.
// Post: item is in the list; length has been incremented.
{    
	NodeType<Itemtype>*  location ;
 	// obtain and fill a node
  location = new  NodeType<Itemtype> ;
	location->info = item ;
	location->next = listData ;
	listData = location ;
	length++ ;
}

Example Trace....

Next

© Lynne Grewe