Thread: Anyone good with linked list.....I am not....

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    1) Don't use NULL. "Real" C++ programmers use 0.

    2)
    Code:
    nodeType *current = first->link;
    nodeType *trail = first;
    
    for (int i = 0; i < pos; i++)
    {
    	current = current->link;
    	trail = trail->link;
    }
    That's a little confusing for me. You have a pointer to the first node(trail) and a pointer to the second node(current), and you are advancing them along the list. If pos is 2, then your for-loop will end after two loops, and you'll have a pointer to the 3rd element(trail) and a pointer to the 4th element(current). What's the point of advancing two pointers along the list? In addition, you need pointers to three nodes to remove a node: a pointer to the node before the node you want to remove, a pointer to the node you want to remove, and pointer to the node after the node you want to remove.

    3) Why perform any calculations and declare variables prior to checking if the list is empty?
    Code:
    if (first == NULL)
    {
    	cout << "List is Empty" << endl;
    }
    4)
    Code:
    if (current->link != NULL)
    current is already several nodes after the node you want to remove(see #1). Hence, current->link is even further down the list, and therefore is irrelevant. Well, not completely irrelevant because if you use the -> operator, that is equivalent to calling the dereference(*) operator and then the member access operator(.), which means you'll be dereferencing a null pointer if you are at the end of the list, and as a result your program will crash. Actually, your program can crash even earlier. What happens if the list has 3 nodes and you try to remove node 10? As you step through the list in your for-loop using ->, you will hit the end up of the list at some point(current will get there first), which means current will be equal to 0, and on the next loop dereferencing current using -> will cause your program to crash.

    When you step through a linked list, there has to be a loop conditional that checks whether you have reached the end of the list.
    Last edited by 7stud; 11-09-2005 at 03:28 PM.

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    131
    Well hear is the progress I am making.....I removed all the templating I had for the sake of working things out....I also removed a couple of functions and am now trying to get the ones I am most concerned about working......as of now everything compiles but I am having a hard time checking my work....this is do to the fact that I don't think I have built my displayFuntion method correctly........also when I do search for a node it ends up crashing......anyone have any ideas......if you need more info let me know...

    Thanks

    Chad

    Code:
    using#ifndef H_LinkedListType
    #define H_LinkedListType
    #include "stdafx.h"
    #include <string>
    #include <fstream>
    #include <iostream>
    #include <cassert>
    using namespace std;
    
    struct nodeType
    {
    	string info;
    	nodeType *link;
    };
    
    class linkedListType
    {
    	friend ostream& operator<<(ostream&, const linkedListType&);
    
    public:
        const linkedListType& operator=(const linkedListType&); 
        void initializeList(); 
        bool isEmptyList();
        int length();
        void destroyList();
        void insertFirst(string name);
        void insertLast(string name);
    
    ///////////////////////////////H E L P ///////////////////////////
    	void getKThElement(int pos); 
    	void linkedListType::Display_List();
    	void deteteKthElement(int pos);
    //////////////////////////////////////////////////////////////////
    
        linkedListType(); 
        ~linkedListType();   
     
    protected:
        int count;		
        nodeType *first; 
        nodeType *last;  
    };
    
    bool linkedListType::isEmptyList()
    {
    	return(first == NULL);
    }
    
    linkedListType::linkedListType()// default constructor
    {
    	first = NULL;
    	last = NULL;
    	count = 0;
    }
    
    void linkedListType::destroyList()
    {
    	nodeType *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 memory occupied by temp
    	}
    
    	last = NULL;	//initialize last to NULL; first has already
                       //been set to NULL by the while loop
     	count = 0;
    }
    
    void linkedListType::initializeList()
    {
    	destroyList(); //if the list has any nodes, delete them
    }
    
    int linkedListType::length()
    {
     	return count;
    }  // end length
    
    ////////////////////////////Help//////////////////////////////
    void linkedListType::Display_List()
    {  
    	nodeType *temp;
    	last = NULL;
        temp = first;
    	
         
    	cout << endl;
        if (first == NULL)
    	cout << "The list is empty!" << endl;
        else
    		{ 
    			while (temp != NULL)
    			{  
    			// Display details for what temp points to
    			cout << "Name: " << temp->info << flush;
    		//	if (temp == current)
    		//	cout << " <-- Current node";
    		//	cout << endl;
    			temp = temp->link;
    	   }
    	 cout << "End of list!" << endl;
         }
      }
    /////////////////////////////H E L P///////////////////////////
    void linkedListType::getKThElement(int pos)
    {   
    	nodeType *current = first->link;
    	nodeType *trail = first;
    	bool found;
    	int count = 0;
        
    	if (first == NULL)//First check if the list is empty....
    	{
    		cout << "The list is Empty!" << endl;
    	}
    	else
    	{
    		if (pos == count && pos == NULL)//Then check to see if pos is the last
    		{								//node
    			current = first; //set current to the first node
    			first = first->link; //set first to the second node
    			count--;//update count
    			if(first == NULL)    //list had only one node
    				last = NULL; //set last to NULL(0)
    			delete current; //delete the current node
    		}
    		else
    		{
    			found = false;
    			current = first->link;  //set current to point to the 
        
    			//Search for node
    			while((!found) && (current != NULL))//While found is false && current is 
    			{									//not the last node 
      				    count++;  //get the total number of nodes
    					current = current-> link; //advance through the list
    			} 
    
    			if(count >= pos) //Check to see if pos is found 
    			{
    				found = true; //if so its there
    			}
    			else
    			{
    				cout<<"Count > than pos";
    			//	return 0;
    			}
    
    			if(found) //if found then delete the node
    			{
    				current=first;
    				for(count=0; count != pos; count++)
    				{
    					trail=current;
    					current = current-> link;
    				}
    				if(last == current)      //node to be deleted was 
                                         //the last node
    					last = trail;  //Another special case update the value of last
    				else
    				{
    					trail->link = current->link;
    				}					
    				cout << "You just found: " << current->info << endl;  
    			}
    			else
    				cout<<"Item to be found is not in the list."<<endl;
    		}
    	} 
    }
    /////////////////////////////////////////////////////////////////
    
    void linkedListType::insertFirst(string name)
    {
    	nodeType *newNode; //pointer to create the new node
    
    	newNode = new nodeType; //create the new node
    
    	assert(newNode != NULL);	//If unable to allocate memory, 
     								//terminate the program
    
    	newNode->info = name; 	   //store the new item in the node
    	newNode->link = first;        //insert newNode before first
    	first = newNode;              //make first point to the 
                                     //actual first node
    	count++; 			   //increment count
    
    	if(last == NULL)   //if the list was empty, newNode is also 
                          //the last node in the list
    		last = newNode;
    }
    
    /////////////////////////////////H E L P////////////////////////////
    void linkedListType::deteteKthElement(int pos)
    {
    	nodeType *current = first->link;
    	nodeType *trail = first;
    	bool found;
    	int count = 0;
        
    	if (first == NULL)//First check if the list is empty....
    	{
    		cout << "The list is Empty!" << endl;
    	}
    	else
    	{
    		if (pos == count && pos == NULL)//Then check to see if pos is the last
    		{								//node
    			current = first; //set current to the first node
    			first = first->link; //set first to the second node
    			count--;//update count
    			if(first == NULL)    //list had only one node
    				last = NULL; //set last to NULL(0)
    			delete current; //delete the current node
    		}
    		else
    		{
    			found = false;
    			current = first->link;  //set current to point to the 
        
    			//Search for node
    			while((!found) && (current != NULL))//While found is false && current is 
    			{									//not the last node 
      				    count++;  //get the total number of nodes
    					current = current-> link; //advance through the list
    			} 
    
    			if(count >= pos) //Check to see if pos is found 
    			{
    				found = true; //if so its there
    			}
    			else
    			{
    				cout<<"Count > than pos";
    			//	return 0;
    			}
    
    			if(found) //if found then delete the node
    			{
    				current=first;
    				for(count=0; count != pos; count++)
    				{
    					trail=current;
    					current = current-> link;
    				}
    				if(last == current)      //node to be deleted was 
                                         //the last node
    					last = trail;  //Another special case update the value of last
    				else
    				{
    					trail->link = current->link;
    				}
    					
    				delete current;  //delete the node from the list
    
    			}
    			else
    				cout<<"Item to be deleted is not in the list."<<endl;
    		}
    	} 
    }
    ////////////////////////////////////////////////////////////////////
    
    //Overloading the stream insertion operator
    ostream& operator<<(ostream& osObject, const linkedListType& list)
    {
    	nodeType *current; //pointer to traverse the list
    
    	current = list.first;   //set current so that it points to 
    					   //the first node
    	while(current != NULL) //while more data to print
    	{
    	   osObject<<current->info<<" ";
    	   current = current->link;
    	}
    	return osObject;
    }
    
    linkedListType::~linkedListType() // destructor
    {
    	destroyList(); 
    }//end destructor
    
    //overload the assignment operator
    const linkedListType& linkedListType::operator=
       	 	 		(const linkedListType& otherList)
    { 
         
    	if(this != &otherList) //avoid self-copy
    	{
    				///copy list
    	}//end else
    
    	return *this; 
    }
    
    void displayMenu()
    {
    	cout << "Select one of the following:" << endl;
    	cout << "1: To search for a node" << endl;
    	cout << "2: To search and delete a node" << endl;
    	cout << "3: Add Name" << endl;
    	cout << "0: EXIT" << endl;
    }
    
    void controller(int i)
    {
    	string name;
    	int pos;
    	linkedListType link;
    
    			if (i == 1)
    			{
    				cout << "Enter the number of the Node to Search For: ";
    				cin >> pos;
    				link.getKThElement(pos);
    			}
    			else if (i == 2)
    			{
    				cout << "Enter the Name of the Node you want to delete: ";
    				cin >> pos;
    				link.deteteKthElement(pos);
    			}
    			else if (i == 3)
    			{
    				cout << "Add Name: ";
    				cin >> name;
    				link.insertFirst(name);
    			}			
    			else
    			{
    				cout << "Invalid Selection" << endl;
    			}
    }
    
    void GetInput()
    {
    	int i;
    	linkedListType link;
    do
    	{
    		link.Display_List();
    		displayMenu();
    		cout << "Please select a number from below: " << flush;
    		cin >> i;
    		controller(i);
    	}
    	while (i != 0);
    }
    
    int _tmain()
    {
    	GetInput();
    	return 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. help! Placement of nodes in a Linked List
    By lostmyshadow in forum C Programming
    Replies: 6
    Last Post: 12-17-2007, 01:21 PM
  2. circular doubly linked list help
    By gunnerz in forum C++ Programming
    Replies: 5
    Last Post: 04-28-2007, 08:38 PM
  3. Linked List Help
    By CJ7Mudrover in forum C Programming
    Replies: 9
    Last Post: 03-10-2004, 10:33 PM
  4. linked list recursive function spaghetti
    By ... in forum C++ Programming
    Replies: 4
    Last Post: 09-02-2003, 02:53 PM
  5. 1st Class LIST ADT
    By Unregistered in forum C++ Programming
    Replies: 1
    Last Post: 11-09-2001, 07:29 PM