12 Replies - 1394 Views - Last Post: 11 December 2012 - 02:18 PM Rate Topic: -----

#1 caoais  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 17-April 12

Help with printing last value in linked list

Posted 11 December 2012 - 10:50 AM

I've been stuck on this for hours. I cannot get 'last' to print its value. When I run through the debugger, it skips the line where I'm trying to assign 'last' to the pointer on line 51 in linkedList.h. I get a segmentation fault. Thanks in advance!


linkedList.h

#include <iostream>
#include <assert.h>
using namespace std;

template <class T>
class linkedList
{
private:
   struct listNode   // declare structure for nodes
    {
      T value;
      listNode * next;
      listNode(T value1, listNode * next1 = NULL)
      {
         value = value1;    // for info in node
         next = next1;      // for link in node
      }
    };

    listNode * head;           // List head pointer
    listNode * last;            // list last pointer
    int count;

public:
    linkedList() { head = NULL; }    //Constructor
    ~linkedList();                    // Destructor
    void addNode(T value);
    void displayFirst() const;
    void displayLast() const;
};
template<class T>
void linkedList<T>::displayFirst() const
{
    listNode *nodePtr;   // to move through the list
    nodePtr = head;
    cout << "The first value is " << head->value;
}

template <class T>
void linkedList<T>::displayLast() const
{
    //listNode * nodePtr = head;      // pointer at head
    listNode *nodePtr;   // to move through the list
    nodePtr = head;
        while (nodePtr != NULL)
           {
            nodePtr = nodePtr->next; // move to next node

                if (nodePtr->next = (NULL))
                {
                     nodePtr = last;     // <------  skips here!! 
                }
            cout << "The last value is " << last->value;
           }  // end while
}

//----------------------------------------------
// Adds a new element to the end of the list.
//----------------------------------------------
template <class T>
void linkedList<T>::addNode(T value)
{
   if (head == NULL)  // is the list is empty
    head = new listNode(value);
   else		// The list is not empty.
   {
      // Use nodePtr to traverse the list
      listNode * nodePtr = head;
        while (nodePtr->next != NULL)
            nodePtr = nodePtr->next;

      // nodePtr->next is NULL so nodePtr points to the last node.
      // Create a new node and put it after the last node.
      nodePtr->next = new listNode(value);


    }  // end else
}  // end addNode

//------------------------------------------------------
// Destructor deallocates the memory used by the list.
//------------------------------------------------------
template <class T>
linkedList<T>::~linkedList()
{
    count = 0;
   listNode * nodePtr = head;  // Start at head of list
   while (nodePtr != NULL)
   {
      // trash keeps track of node to be deleted
      listNode * trash = nodePtr;
      nodePtr = nodePtr->next;  // Move to the next node
      delete trash;
   }  // end while
}  // end destructor



main.cpp
#include <iostream>
#include <cstdlib>
using namespace std;

#include "linkedList.h"

void repeat();  // function to repeat program

int main()
{
   linkedList<string> list;
   linkedList<string> otherList;
   string name;

   cout << "Add 5 names to the list:\n";
   for (int count = 0; count < 5; count++)
   {
      cout << "Name #" << count + 1 << ": ";
      getline(cin, name);
      list.addNode(name);
   }

   list.displayFirst();
   cout << endl;
   list.displayLast();

   // list.~linkedList();
    repeat();
   return 0;
}

//--------------- repeat --------------------------------------
// function to repeat program
//-------------------------------------------------------------
void repeat()
{
    char x;
    cout << "Would you like to run the program again? [y/n]: ";
    cin >> x;
    cin.ignore(10, '\n');
    cout << endl;

        if (x == 'y' || x == 'Y')

            main();
        else if (x == 'n' || x == 'N')
        {
            cout << "Goodbye";
            exit(0);
        }
        else if (x != 'n' || x != 'N' || x != 'y' || x != 'Y')
        {
            cout << "Invalid choice.  ";
            repeat(); 		//  function call to repeat to repeat
        }
} // end void repeat




Is This A Good Question/Topic? 0
  • +

Replies To: Help with printing last value in linked list

#2 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 4364
  • View blog
  • Posts: 12,182
  • Joined: 18-April 07

Re: Help with printing last value in linked list

Posted 11 December 2012 - 11:06 AM

I think you mean if (nodePtr->next == NULL). Notice the double equal signs. Here we are checking if next is NULL. Once you reach this stage, and you know that next is null, you can return nodePtr because it is the last item in the list.

I really hope that helps you out. :)
Was This Post Helpful? 1
  • +
  • -

#3 caoais  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 17-April 12

Re: Help with printing last value in linked list

Posted 11 December 2012 - 11:28 AM

thanks Martyr2, I still get the same result. It skips right over that assignment statement. Maybe I'm not moving through the list right?
Was This Post Helpful? 0
  • +
  • -

#4 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5884
  • View blog
  • Posts: 12,769
  • Joined: 16-October 07

Re: Help with printing last value in linked list

Posted 11 December 2012 - 11:41 AM

if (head == NULL)  // is the list is empty
    head = new listNode(value);
   else     // The list is not empty.
   {



Where does last get set?
Was This Post Helpful? 2
  • +
  • -

#5 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 4364
  • View blog
  • Posts: 12,182
  • Joined: 18-April 07

Re: Help with printing last value in linked list

Posted 11 December 2012 - 11:45 AM

Take a look at this piece here....

while (nodePtr != NULL) //<-- Ok nodePtr is not null
{
    nodePtr = nodePtr->next; //<-- nodePtr->next may be null though

    if (nodePtr->next == NULL) //<-- We are not testing if nodePtr is now null
    {
       nodePtr = last; 
    }
    cout << "The last value is " << last->value;
}



Let's make some adjustments...

while (nodePtr != NULL) //<-- Ok nodePtr is not null
{
    if (nodePtr->next == NULL) //<-- Now we are seeing if next is null
    {
       last = nodePtr; //<-- It was, so nodePtr is the last node, assign it to last
       cout << "The last value is " << last->value;
       return; //<-- Bail, we hit the last node now. No use continuing.
    }

    nodePtr = nodePtr->next; //<-- We move to next because we haven't reached the last node
}



Experiment with this idea and how we are moving through the list. Notice we check the current node, if it is valid we look at the next node. As soon as that hits NULL we know the current node is the last node.

:)
Was This Post Helpful? 1
  • +
  • -

#6 caoais  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 17-April 12

Re: Help with printing last value in linked list

Posted 11 December 2012 - 12:27 PM

thanks baavgai, I was thinking that last was not getting assigned anywhere.

so Martyr2, it now steps through that sequence five times and it assigns last to nodePtr.
after this:
cout << "The last value is " << last->value;



it calls back to itself in the main.cpp and crashes
list.displayFirst();
cout << endl;
list.displayLast();    // <------ calls back here and crashes


Was This Post Helpful? 0
  • +
  • -

#7 caoais  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 17-April 12

Re: Help with printing last value in linked list

Posted 11 December 2012 - 12:34 PM

also when I use: last = nodePtr; like you suggested it gives the following error. if I use nodePtr = last; it compiles.

error: assignment of data-member 'linkedList<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >::last' in read-only structure
Was This Post Helpful? 0
  • +
  • -

#8 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5884
  • View blog
  • Posts: 12,769
  • Joined: 16-October 07

Re: Help with printing last value in linked list

Posted 11 December 2012 - 12:37 PM

template <class T>
void linkedList<T>::addNode(T value) {
	if (head == NULL) {
		last = head = new listNode(value);
	} else {
		// you don't set last here, either
		// you're looping to find a tail you've already defined
		// assign your new node to be after the current tail
		// and then move the tail
		// it's two whole lines...
	}
}


Was This Post Helpful? 1
  • +
  • -

#9 caoais  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 17-April 12

Re: Help with printing last value in linked list

Posted 11 December 2012 - 01:36 PM

ok, so this takes care of assigning last?
last = head = new listNode(value);


I'm trying to do what you said with no luck, think I've been looking at this for way too long.
listNode * nodePtr;
last->next = new listNode(value);    
 nodePtr = last->next;


Was This Post Helpful? 0
  • +
  • -

#10 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5884
  • View blog
  • Posts: 12,769
  • Joined: 16-October 07

Re: Help with printing last value in linked list

Posted 11 December 2012 - 01:45 PM

// listNode * nodePtr; get rid of this
last->next = new listNode(value); // this is correct
// almost nodePtr = last->next;
// change the value of last instead



View Postcaoais, on 11 December 2012 - 03:36 PM, said:

ok, so this takes care of assigning last?
last = head = new listNode(value);


Yeah, that's just one of those nasty little Cisms. Same as:
head = new listNode(value);
last = head;



It actually cascades the assignment backwards, so it's more like:
last = (head = new listNode(value));


You can ignore that, but it's neat.
Was This Post Helpful? 1
  • +
  • -

#11 caoais  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 17-April 12

Re: Help with printing last value in linked list

Posted 11 December 2012 - 01:57 PM

View Postbaavgai, on 11 December 2012 - 01:45 PM, said:

// listNode * nodePtr; get rid of this
last->next = new listNode(value); // this is correct
// almost nodePtr = last->next;
// change the value of last instead



View Postcaoais, on 11 December 2012 - 03:36 PM, said:

ok, so this takes care of assigning last?
last = head = new listNode(value);


Yeah, that's just one of those nasty little Cisms. Same as:
head = new listNode(value);
last = head;



It actually cascades the assignment backwards, so it's more like:
last = (head = new listNode(value));


You can ignore that, but it's neat.


I quoted your last reply and there was all that about the assignments that doesn't show up until I quote...

if I get rid of the 'listNode * nodePtr;' I get an error of nodePtr was not declared in this scope.

I changed the value of last to nodePtr...not sure what else to change it to.
Was This Post Helpful? 0
  • +
  • -

#12 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5884
  • View blog
  • Posts: 12,769
  • Joined: 16-October 07

Re: Help with printing last value in linked list

Posted 11 December 2012 - 02:07 PM

From your code:
nodePtr = nodePtr->next;  // Move to the next node



Applying that logic to your current puzzle:
last->next = new listNode(value);
last = last->next; // Move last to next node


Was This Post Helpful? 1
  • +
  • -

#13 caoais  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 17-April 12

Re: Help with printing last value in linked list

Posted 11 December 2012 - 02:18 PM

I can't thank you enough baavgai!! That did it! I've been staring at this most of the day.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1