5 Replies - 1009 Views - Last Post: 12 November 2012 - 06:58 PM Rate Topic: -----

#1 alias120  Icon User is offline

  • The Sum over All Paths
  • member icon

Reputation: 122
  • View blog
  • Posts: 700
  • Joined: 02-March 09

Pointer to Node in Linked List

Posted 02 June 2010 - 10:12 PM

I have a question in regards to declaring pointers of type class. I just finished a short program that produces the fibonacci sequence, populating a linked list with each number. To display the sequence, I used a for loop to traverse the list and print each nodes integer value. Initially, when calling the function to run the loop, the loop would never execute. Below is the for loop.

for(temp = first; temp != NULL; temp = temp->next)
{
    cout<<temp->data<<", ";
}



Now, I was able to figure out that the pointer 'first' was where the problem is occuring. Originally I declared first as

Node *first;



within the Linked List class. I then moved the declaration of first to the Node class. This alone fixed my problem and allowed the program to execute as desired. I am trying to figure out why this is. My guess is that declaring first within the Node class allows it to actually be referenced at each Node, allowing you to have a point of reference (no pun intended) when populating your list? Incase I was too vague in my question, I will go ahead and post the full program below for your reference. Thanks in advance for your feedback!

#include<iostream>

using namespace std;


class Node  
{		
	Node *next;

	friend class LinkedList;

	~Node(){delete first; first = NULL; delete next; next = NULL;};

public:

	int data;

}*first;
 



class LinkedList

{

 friend class FiboSequence;


public:

    LinkedList(){first = NULL;}

    ~LinkedList(){};

    void addToList(int fiboNum);

    void printList();

};

 
void LinkedList::addToList(int fiboNum)

{
	Node *new_pointer;
	Node *temp;
     
	if(first == NULL)
	{

		first = new Node;

		first->data = fiboNum;

		first->next = NULL;
	}

	else

	{

		new_pointer = first;

		while(new_pointer->next != NULL)
			new_pointer = new_pointer->next;

		temp = new Node;

		temp->data = fiboNum;

		temp->next = NULL;

		new_pointer->next = temp;
	}



}


void LinkedList::printList()

{

      Node *temp;
      int i = 0;

      for(temp = first; temp != NULL; temp = temp->next)

      {
			
          i++;
          cout<<temp->data<<", ";

		  switch(i)
		  {
		  case 16:
			  cout<<endl;
			  break;
		  case 26:
			  cout<<endl;
			  break;
		  case 34:
			  cout<<endl;
			  break;
		  case 40:
			  cout<<endl;
			  break;
		  }


      }
}



class FiboSequence

{

      int current_num;

      int added_num;

      int result;

 
public:

 

      FiboSequence();

      ~FiboSequence(){};

      void startSequence();

      void getList();

 
};

 

FiboSequence::FiboSequence()

{

      current_num = 1;

      added_num = 1;

      result = 0;

}

 

void FiboSequence::startSequence()

{

      int i = 0;

      LinkedList obj;

      cout<<current_num<<", ";

      cout<<added_num<<", ";

 
      while(i < 40)

      {

            i++;

            result = current_num + added_num;

            obj.addToList(result);

	    current_num = added_num;

            added_num = result;

      }

}
 

int main()

{

      LinkedList obj;

      FiboSequence obj2;

      cout<<"Press any key to begin populating Linked List with \n"

            <<"Fibonacci Sequence..."<<endl;

      cout<<endl;

      cin.get();

      cout<<"List Populated, below is the Fibonacci Sequence."<<endl;

      cout<<endl;
	  
      obj2.startSequence();

      obj.printList();

      cout<<endl;


      cin.get();
      return 0;

}


This post has been edited by alias120: 02 June 2010 - 10:13 PM


Is This A Good Question/Topic? 0
  • +

Replies To: Pointer to Node in Linked List

#2 Oler1s  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1395
  • View blog
  • Posts: 3,884
  • Joined: 04-June 09

Re: Pointer to Node in Linked List

Posted 02 June 2010 - 11:31 PM

Your code is flawed. I'll refer to a cleaned up version of your code:

#include <iostream>
using namespace std;

class Node
{
    Node *next;
    friend class LinkedList;
     ~Node ()
    {
        delete first;
          first = NULL;
        delete next;
          next = NULL;
    };

  public:
    int data;
} *first;

class LinkedList
{
    friend class FiboSequence;

  public:
      LinkedList ()
    {
        first = NULL;
    }

     ~LinkedList ()
    {
    };
    void addToList (int fiboNum);
    void printList ();
};

void LinkedList::addToList (int fiboNum)
{
    Node *new_pointer;
    Node *temp;

    if (first == NULL)
      {
          first = new Node;
          first->data = fiboNum;
          first->next = NULL;
      }
    else
      {
          new_pointer = first;

          while (new_pointer->next != NULL)
              new_pointer = new_pointer->next;

          temp = new Node;
          temp->data = fiboNum;
          temp->next = NULL;
          new_pointer->next = temp;
      }
}

void LinkedList::printList ()
{
    Node *temp;
    int i = 0;

    for (temp = first; temp != NULL; temp = temp->next)
      {
          i++;
          cout << temp->data << ", ";

          switch (i)
            {
            case 16:
                cout << endl;
                break;
            case 26:
                cout << endl;
                break;
            case 34:
                cout << endl;
                break;
            case 40:
                cout << endl;
                break;
            }
      }
}

class FiboSequence
{
    int current_num;
    int added_num;
    int result;

  public:
    FiboSequence ();
    ~FiboSequence ()
    {
    };
    void startSequence ();
    void getList ();
};

FiboSequence::FiboSequence ()
{
    current_num = 1;
    added_num = 1;
    result = 0;
}

void FiboSequence::startSequence ()
{
    int i = 0;
    LinkedList obj;
    cout << current_num << ", ";
    cout << added_num << ", ";

    while (i < 40)
      {
          i++;
          result = current_num + added_num;
          obj.addToList (result);
          current_num = added_num;
          added_num = result;
      }
}

int main ()
{
    LinkedList obj;
    FiboSequence obj2;
    cout << "Press any key to begin populating Linked List with \n"
        << "Fibonacci Sequence..." << endl;
    cout << endl;
    cin.get ();
    cout << "List Populated, below is the Fibonacci Sequence." << endl;
    cout << endl;
    obj2.startSequence ();
    obj.printList ();
    cout << endl;
    cin.get ();
    return 0;
}



Line numbers correspond to this version of the code. I've just reformatted i (somewhat). Clean up the code further on your own time.

     ~Node ()
    {
        delete first;
          first = NULL;
        delete next;
          next = NULL;



Why is your destructor for a node managing something that is not a member? In fact, the node destructor should do nothing. It consists of two things, data, and pointer to another node. Data is not dynamically allocated. There is nothing to manage. delete the next pointer is a bad mistake. You do not delete what you do not allocate. This node does not manage the memory it points to. It simply points somewhere. How that other node is allocated and when it gets deallocated is not the destructor's concern.

Your linked list, however, does manage the nodes. The various member functions allocate memory. Yet the destructor is empty. Apparently, your linked list is happy to grab memory, but is hands off on cleaning up after itself.

I don't know what caused your original problem. Your approach to fix it is flawed. Your code was broken, so you resorted to chicken voodoo, making unjustified changes to get the problem to disappear. Rather than discovering the mistake, you're making changes hoping to see the problem disappear. It may, or it may not. But a working program is neither a sign of correctness nor robustness. It may break spectacularly on another computer, or 5 minutes later.
Was This Post Helpful? 0
  • +
  • -

#3 alias120  Icon User is offline

  • The Sum over All Paths
  • member icon

Reputation: 122
  • View blog
  • Posts: 700
  • Joined: 02-March 09

Re: Pointer to Node in Linked List

Posted 03 June 2010 - 12:15 AM

I did not say the program was perfect. This is my first attempt at writing a Linked List using OOP and much of this program is about learning new concepts. I did not have any justification for moving the pointer other than an un-educated guess as to what the problem might be. This is not the order in which I like to do things. It would be great if every problem I come across is solved through initial research and not blind luck. Sometimes it does not happen this way, and now I am trying to learn what did happen. I appreciate your expertise Oler1s, and I apologize if I presented this program as something other than a learning experience. I will take my question to the books and see if I can resolve an answer there.


-alias
Was This Post Helpful? 0
  • +
  • -

#4 Oler1s  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1395
  • View blog
  • Posts: 3,884
  • Joined: 04-June 09

Re: Pointer to Node in Linked List

Posted 03 June 2010 - 11:05 AM

Quote

I did not say the program was perfect.
I know you didn't. Irrelevant point.

Quote

I did not have any justification for moving the pointer other than an un-educated guess as to what the problem might be.
In other words, chicken voodoo. This is precisely what I criticized. It's one thing to make guesses, but programmers should behave like scientists. A hypothesis backed by technical speculation. Gathering evidence and forming conclusions. Instead, your approach is that of chicken voodoo.

Quote

Sometimes it does not happen this way, and now I am trying to learn what did happen.
This is not a good approach. A working program does not reveal correctness or guarantees of behaviors.

The critical aspect to programming is correctness of problem solving. Not knowledge. As a programmer, you are an artist. You are creating something new, something you haven't done before. You don't know what the answer is. You don't know what the problem is. What you rely on is your ability to break down and solve problems.

You seem taken aback that I criticize you for things you don't know. That's false. I criticize you for bad problem solving approach. One dire mistake you made is to think that a working program is also a correct program.

What you should have done is taken the original problem and gathered evidence with debugging techniques. Even if you couldn't solve the issue, you could present code plus the evidence you had gathered, with your thoughts and conjectures. But your original post revealed a different mentality.
Was This Post Helpful? 0
  • +
  • -

#5 alias120  Icon User is offline

  • The Sum over All Paths
  • member icon

Reputation: 122
  • View blog
  • Posts: 700
  • Joined: 02-March 09

Re: Pointer to Node in Linked List

Posted 03 June 2010 - 05:50 PM

Thank you for your response Oler1s. I must have been tired last night, hence why I sounded taken aback by your comments. I did not perform the proper research to adequately solve the problem at hand, and this was my downfall. I seem to have forgotten for a minute the reason I am here, to learn and be critiqued by the intelligent individuals of this community. So again, thank you for your feedback Oler1s and I will remember what you said about the "chicken voodoo" I performed above.


-alias
Was This Post Helpful? 0
  • +
  • -

#6 Switters  Icon User is offline

  • D.I.C Head

Reputation: 25
  • View blog
  • Posts: 110
  • Joined: 03-June 12

Re: Pointer to Node in Linked List

Posted 12 November 2012 - 06:58 PM

View PostOler1s, on 03 June 2010 - 11:05 AM, said:

Quote

I did not say the program was perfect.
I know you didn't. Irrelevant point.

Quote

I did not have any justification for moving the pointer other than an un-educated guess as to what the problem might be.
In other words, chicken voodoo. This is precisely what I criticized. It's one thing to make guesses, but programmers should behave like scientists. A hypothesis backed by technical speculation. Gathering evidence and forming conclusions. Instead, your approach is that of chicken voodoo.

Quote

Sometimes it does not happen this way, and now I am trying to learn what did happen.
This is not a good approach. A working program does not reveal correctness or guarantees of behaviors.

The critical aspect to programming is correctness of problem solving. Not knowledge. As a programmer, you are an artist. You are creating something new, something you haven't done before. You don't know what the answer is. You don't know what the problem is. What you rely on is your ability to break down and solve problems.

You seem taken aback that I criticize you for things you don't know. That's false. I criticize you for bad problem solving approach. One dire mistake you made is to think that a working program is also a correct program.

What you should have done is taken the original problem and gathered evidence with debugging techniques. Even if you couldn't solve the issue, you could present code plus the evidence you had gathered, with your thoughts and conjectures. But your original post revealed a different mentality.


Your tone is not very constructive to a novice (Edit: or anyone, for that matter). I suppose free advice can be delivered in any manner that someone wishing to dedicate the time to do so chooses, but surely there is a more pleasant way to say things that wouldn't sound so condescending.

This post has been edited by Switters: 12 November 2012 - 07:02 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1