Linked lists omissions by author, such as not defining NULL

  • (3 Pages)
  • +
  • 1
  • 2
  • 3

35 Replies - 4182 Views - Last Post: 10 March 2012 - 11:24 PM Rate Topic: -----

#1 mgrex  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 182
  • Joined: 25-March 10

Linked lists omissions by author, such as not defining NULL

Posted 06 March 2012 - 08:16 PM

The main reason I've made new thread is because I just began a new chapter.

For the following code, the author only disclosed lines 3 to 28.



NumberList.cpp
#include "NumberList.h"

void NumberList::appendNode(double num) 
{ 
	ListNode *newNode;		// To allocate & point to a new node 
	ListNode *nodePtr;		// To move through the list 

	// Allocate a new node and store num there. 
	newNode = new ListNode; 
	newNode->value = num; 
	newNode->next = NULL; //ERROR:: Identifer "NULL" is undefined

	// If there are no nodes in the list make newNode the 1st node. 
	if(!head) 
		head = newNode; 
	else // Otherwise, insert newNode at end. 
	{ 
		// Initialize nodeptr to head of list. 
		nodePtr = head; 

		// Find the last node in the list . 
		while (nodePtr->next) 
			nodePtr = nodePtr->next; 

		// Insert newNode as the last node . 
		nodePtr->next = newNode;
	} 
} 


NumberList.h
// Specification file for the NumberList class 
#ifndef NUMBERLIST_H 
#define NUMBERLIST_H

class NumberList 
{ 
private: 
	// Declare a structure for the list 
	struct ListNode 
	{ 
		double value;			// The value in this node 
		struct ListNode *next;	// To point to the next node 
	}; 

	ListNode *head;				// List head pointer

public: 
	// Constructor: notice the constructor initializes the head pointer to NULL
	// This establishes an empty linked list. 
	NumberList() 
	{	head = NULL;	} 

	// Destructor: destroys  the list by deleting all its nodes. 
	~NumberList();

	// Linked list operations 
	// These functions are defined in NumberList.cpp.
	void appendNode(double); 
	void insertNode(double); 
	void deleteNode(double); 
	void displayList() const; 
}; 
#endif 


 


Pr17-01.cpp
// This program demonstrates a simple append 
// operation on a linked list . 
#include <iostream> 
#include "NumberList.h" 
using namespace std; 
int main() 
{ 
	// Define a NumberList object. 
	NumberList list; 
	// Append some values to the list. 
	list.appendNode(2.5); 
	list.appendNode(7.9); 
	list.appendNode(12.6); 

	system("pause");
	return 0 ; 
}

This post has been edited by r.stiltskin: 06 March 2012 - 08:40 PM
Reason for edit:: Fixed the code tags.


Is This A Good Question/Topic? 0
  • +

Replies To: Linked lists omissions by author, such as not defining NULL

#2 r.stiltskin  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1833
  • View blog
  • Posts: 4,927
  • Joined: 27-December 05

Re: Linked lists omissions by author, such as not defining NULL

Posted 06 March 2012 - 08:42 PM

Do you have a question?
Was This Post Helpful? 0
  • +
  • -

#3 David W  Icon User is offline

  • DIC supporter
  • member icon

Reputation: 275
  • View blog
  • Posts: 1,764
  • Joined: 20-September 08

Re: Linked lists omissions by author, such as not defining NULL

Posted 06 March 2012 - 11:47 PM

You seem to be on your way to writing code to handle simple, single link, linked lists ... You will find much here at DIC to help ... check the snippets and tutorials especially.

You might like to see these snippets for future ref...

Template class List (using a plain linked-list) ...
http://www.dreaminco...snippet2617.htm

Template class List with front, rear and size
Now with merge sort, insert sort, remove duplicates, copy constructor, overloaded assignment
http://www.dreaminco...snippet3448.htm

Template List1IterNode.h
a template 'single-link' linked-list with 'merge sort' and 'insert sort and has private class members: 'pFront', 'pRear', 'size', 'is_sorted' ... AND now includes template class Node and template class Iter
http://www.dreaminco...snippet5982.htm


As a matter of 'best coding practice' ... it is usually good to put your most common case first, even though you may, while developing, like to deal, at the beginning, with all the exceptional cases.

For example, your 'final' version may look like the following ...

#include "NumberList.h"

void NumberList::appendNode(double num) 
{ 
	// Allocate a new node and store num there. 
	ListNode* newNode = new ListNode; 
	newNode->value = num; 
	newNode->next = 0;

	// Place most common case first ...  i.e. case of head != 0
	if( head ) // then find address of last node in list ... i.e. traverse the whole list
	{
		// firstly, initialize a nodeptr to address of head of list. 
		ListNode* nodePtr = head; 

		// Now find the last node in the list ... 
		while( nodePtr->next ) // i.e while( nodePtr->next != 0 )
			nodePtr = nodePtr->next; 
		// Now link this in as the last node in the list ... 
		nodePtr->next = newNode;
	}
	else // Otherwise, list was empty ... i.e. head was 0, so now can set head to ...
	{  
		head = newNode; 
	} 
} 



Also ...

it is good to avoid using system commands to keep your code portable.

You can use something like this instead:

cout << "Press 'Enter' to continue/exit ... " << flush;
// you may also need the next command ... // commented out below
// if you have not been keeping cin stream 'flushed' 
// as you go, after input via cin ...
// cin.sync(); // 'flush' cin stream ...
cin.get(); // wait for 'Enter' key to be pressed ...


This post has been edited by David W: 07 March 2012 - 12:25 AM

Was This Post Helpful? 0
  • +
  • -

#4 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 5960
  • View blog
  • Posts: 23,238
  • Joined: 23-August 08

Re: Linked lists omissions by author, such as not defining NULL

Posted 07 March 2012 - 04:15 AM

When you have a question or problem, state it in the BODY of your post. Don't make us go looking through code/comments to find it.

newNode->next = NULL; //ERROR:: Identifer "NULL" is undefined

Answer in here.
Was This Post Helpful? 1
  • +
  • -

#5 mgrex  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 182
  • Joined: 25-March 10

Re: Linked lists omissions by author, such as not defining NULL

Posted 07 March 2012 - 03:34 PM

I'm sorry for not stating my problem in my post's body.
I tried inserting #include <cstdlib> & #include <cstdio>, to the header and received a compile error. I placed the header in NumberList.h. No luck with placing it in NumberList.cpp, either.

I did get better luck though with cstdio along with using namespace std; where where the output form atleast display “Generating Code”. Also NULL doesn't turn blue.


The main reason I use system(“pause”) is that at times, I have to resort to inserting cin.get() twice (especially if it involves certain types of functions), otherwise the program will shut down quickly.



1>------ Build started: Project: 17_01, Configuration: Debug Win32 ------
1>  NumberList.cpp
1>  Generating Code...
1>  Compiling...
1>  Pr17-01.cpp
1>  Generating Code...
1>Pr17-01.obj : error LNK2019: unresolved external symbol "public: __thiscall NumberList::~NumberList(void)" (??1NumberList@@QAE@XZ) referenced in function _main
1>C:\Path\Ch 17\17_01\Debug\17_01.exe : fatal error LNK1120: 1 unresolved externals
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========


This post has been edited by mgrex: 07 March 2012 - 03:37 PM

Was This Post Helpful? 0
  • +
  • -

#6 #define  Icon User is offline

  • Duke of Err
  • member icon

Reputation: 1276
  • View blog
  • Posts: 4,401
  • Joined: 19-February 09

Re: Linked lists omissions by author, such as not defining NULL

Posted 07 March 2012 - 04:04 PM

7	1>Pr17-01.obj : error LNK2019: unresolved external symbol "public: __thiscall NumberList::~NumberList(void)"



This error is saying the destructor function is missing - ie you need to write one.
Was This Post Helpful? 1
  • +
  • -

#7 r.stiltskin  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1833
  • View blog
  • Posts: 4,927
  • Joined: 27-December 05

Re: Linked lists omissions by author, such as not defining NULL

Posted 07 March 2012 - 04:15 PM

I think that by now you're at a point where you should be reading your compiler messages with a much more discerning eye. Those messages convey information that you should be trying a little harder to understand. They aren't always crystal clear, but you should be able to recognize that unresolved external symbol "public: __thiscall NumberList::~NumberList(void)" has no apparent connection with ERROR:: Identifer "NULL" is undefined.

Realize that the compiler doesn't necessarily generate messages about all of the errors in the program at once. Frequently it reports one or several errors and then quits. When you fix those and try to compile again, it reports a few more errors. You shouldn't immediately conclude that the previous correction caused the new errors. I may simply mean that the compiler is now looking further into the program and discovering errors that it didn't get to before.
Was This Post Helpful? 2
  • +
  • -

#8 mgrex  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 182
  • Joined: 25-March 10

Re: Linked lists omissions by author, such as not defining NULL

Posted 07 March 2012 - 04:29 PM

Nice,

I did the following to the destructor function

From
	~NumberList();


To (still compiled without the ';' after/within the braces)
	~NumberList()
	{}


& Alternatively to (this may be wrong, but the program still compiled)
	~NumberList()
	{	 delete  [] head; }



The program was able to successfully compile. According to the author not output should be displayed by the program. This is only the first program of the chapter, so further problems may arise. Thanks for the help.

This post has been edited by mgrex: 07 March 2012 - 04:31 PM

Was This Post Helpful? 0
  • +
  • -

#9 r.stiltskin  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1833
  • View blog
  • Posts: 4,927
  • Joined: 27-December 05

Re: Linked lists omissions by author, such as not defining NULL

Posted 07 March 2012 - 04:35 PM

That's not good enough for the destructor. head isn't an array per se. It's just a pointer, pointing to the first in a chain of nodes. If you delete head it leaves the rest of the list "dangling". That's a classic example of a memory leak.

Instead, you have to iterate through the entire list -- all of the nodes that have been dynamically allocated, and delete each one. The challenge is to accomplish that without getting lost in the process.
Was This Post Helpful? 1
  • +
  • -

#10 mgrex  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 182
  • Joined: 25-March 10

Re: Linked lists omissions by author, such as not defining NULL

Posted 08 March 2012 - 02:38 PM

Things just gets worse with the book :(. Thankfully there's less than 130 pages to go.

1st off I'd like to dissect the reasons for the error message, in the following LinkedList.h file, which I entered in exactly as the author entered.

Problems are from Lines 84 to 99 I even tried placing the display list function body, right before the Destructor function, and the same problem still resulted. I'd like

// A class template for holding a linked list. 
//The limitation of the NumberList class is that it can only hold double values.

#ifndef LINKEDLIST_H 
#define LINKEDLIST_H 
#include <iostream> 	// For cout and NULL 
using namespace std; 

template <class T> 
class LinkedList 
{ 
private: 
	// Declare a structure for the list. 
	struct ListNode 
	{ 
		T value;					// The value in this node
		struct ListNode *next;		// To point to the next node 
	}; 

	ListNode *head; // List head pointer 

public: 
	// Constructor 
	NumberList() 
		{	head = NULL;	} 

	// Destructor 
	~NumberList()
	{;}

	// Linked list operations 
	void appendNode(T); 
	void insertNode(T); 
	void deleteNode(T);
	void displayList() const; 
};

// Note that the template uses the ==, !=, and < relational operators to compare node values, 
// and it uses the << (line 93) operator with cout to display node values. Any type passed to  
// the template must support these operators. 


//********************************************************
// appendNode appends a node containing the value 
// passed into newValue, to the end of the list. 
//******************************************************** 
template <class T> 
void LinkedList<T>::appendNode(T newValue) 
{ 
	ListNode *newNode;		// To point to a new node 
	ListNode *nodePtr;		// To move through the list 


	// Allocate a new node and store nurn there. 
	newNode = new ListNode; 
	newNode->value = num; 
	newNode->next = NULL; 

	// If there are no nodes in the list make newNode the 1st node. 
	if(!head) 
		head = newNode; 
	// Otherwise, insert newNode at end.
	else 
	{ 
		// Initialize nodePtr to head of list. 
		nodePtr = head; 
		
		// Find the last node in the list. 
		while (nodePtr->next) 
			nodeptr = nodePtr->next; 
		
		// Insert newNode as the last node. 
		nodeptr->next = newNode; 
	}
}

//************************************************** 
// displayList shows the value 
// stored in each node of the linked list 
// pointed to by head. 
//************************************************** 
template <class T> 
void LinkedList<T>::displayList() //Compile Error: unable to match function definition to an existing declaration
{ 
	// To move through the list
	ListNode *nodePtr;			//Error: identifier "ListNode" is undefined
	
	// Position nodePtr at the head of the list. 
	nodePtr = head;			//ERROR: this declaration (nodePtr) has no storage class or type identifer & identifer "head" is undefined

	// While nodeptr points to a node, traverse the list. 
	while (nodePtr)			//ERROR: expected a declaration
	{ 
		// Display the value in this node. 
		cout << nodePtr->value << endl; //ERROR: this declaration (cout) has no storage class or type idenfifer & << expectated a ';'

		// Move to the next node. 
		nodePtr = nodePtr->next; //ERROR: this declaration (nodePtr) has no storage class or type identifer & <error-type> *nodePtr, expression must have poniter to type
	} //Error: expected a declaration
}

//*****************************************************
// The insertNode function inserts a node with 
// newValue copied to its value member. 
//*****************************************************
template <class T> 
void LinkedList<T>::insertNode(T newValue) 
{
	ListNode *newNode;				// A new node 
	ListNode *nodePtr;				// To traverse the list 
	ListNode *previousNode = NULL;	// The previous node 
	
	
	// Allocate a new node and store num there. 
	newNode = new ListNode; 
	newNode->value = num; 
	
	// If there are no nodes in the list make newNode the first node. 
	if(!head) 
	{ 
		head = newNode; 
		newNode->next = NULL; 
	} 
	// Otherwise, insert newNode. 
	else 
	{ 
		// position nodePtr at the head of list. 
		nodePtr = head; 

		// Initialize previousNode to NULL. 
		previousNode = NULL; 

		// Skip all nodes whose value is less than num. 
		while (nodePtr != NULL && nodePtr->value < num) 
		{ 
			previousNode = nodePtr; 
			nodePtr = nodePtr->next; 
		} 

		// If the new node is to be the 1st in the list, 
		// insert it before all other nodes. 
		if (previousNode == NULL) 
		{
			head = newNode; 
			newNode->next = nodePtr; 
		}

		else // Otherwise insert after the previous node. 
		{ 
			previousNode->next = newNode; 
			newNode->next = nodePtr; 
		} 
	} 
} 

//******************************************************** 
// The deleteNode function searches for a node • 
// with searchValue as its value. The node, if found, * 
// is deleted from the l ist and from memory. * 
//******************************************************** 
template <class T> 
void LinkedList<T>::deleteNode(T searchValue) 
{ 
	ListNode *nodePtr;			// To traverse the list 
	ListNode *previousNode;		// To point to the previous node

	// If the list is empty, do nothing. 
	if (!head) 
		return; 
	// Determine if the first node is the one. 
	if (head->value == num) 
	{ 
		nodePtr = head->next; 
		delete head; 
		head = nodePtr; 
	} 
	else 
	{ 
		// Initialize nodePtr to head of list. 
		nodePtr = head; 

		// Skip a11 nodes whose value member is not equal to num.
		while (nodePtr != NULL && nodeptr->value != num) 
		{ 
			previousNode = nodePtr; 
			nodePtr = nodeptr->next;
		} 

		// If nodePtr is not at the end of the list, link the prevLous
		// node to the node after nodePtr, then delete nodePtr.
		if (nodePtr) 
		{
			previousNode->next = nodePtr->next; 
			delete nodePtr;
		}
	} 
} 




//******************************************************** 
// Destructor 
// This function deletes every node in the list.
//******************************************************** 
template <class T> 
LinkedList<T>::~LinkedList() 
{ 
	ListNode *nodeptr;		// To traverse the list 
	ListNode *nextNode;		// To point to the next node 

	// position nodePtr at the head of the list. 
	nodeptr = head; 

	// While nodePtr is not at the end of the list... 
	while (nodePtr != NULL) 
	{ 
		// Save a pointer to the next node . 
		nextNode = norlePtr->next; 
		// Delete the current node. 
		delete nodeptr; 
		// position nodePtr at the next node . 
		nodePtr = nextNode; 
	} 
}
#endif 


This post has been edited by mgrex: 08 March 2012 - 02:39 PM

Was This Post Helpful? 0
  • +
  • -

#11 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 5960
  • View blog
  • Posts: 23,238
  • Joined: 23-August 08

Re: Linked lists omissions by author, such as not defining NULL

Posted 08 March 2012 - 03:09 PM

Declaration:
void displayList() const; 


Implementation:
void LinkedList<T>::displayList()


What's missing in the implementation?

Fixing that will likely fix the others.

EDIT: I had to fix a lot more than that to get this to compile, by the way. Are you copying and pasting the code you're working on here, or re-typing (again) in the edit box?
Was This Post Helpful? 1
  • +
  • -

#12 r.stiltskin  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1833
  • View blog
  • Posts: 4,927
  • Joined: 27-December 05

Re: Linked lists omissions by author, such as not defining NULL

Posted 08 March 2012 - 04:35 PM

What a mess.

Anyone who puts out a textbook with this degree of carelessness doesn't deserve to have it read, much less bought, by anyone. It's really a disgrace.

Nevertheless, by now you should be completely capable of correcting all the syntax errors in that code just by reading the error messages carefully, keeping in mind these three things:
- function declarations and their definitions must agree in return type, function name, arguments (number, order and types), and constness
- the variable names used in the function bodies must agree with the corresponding names in the function signatures
- C++ is case-sensitive.
Was This Post Helpful? 0
  • +
  • -

#13 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 5960
  • View blog
  • Posts: 23,238
  • Joined: 23-August 08

Re: Linked lists omissions by author, such as not defining NULL

Posted 08 March 2012 - 04:44 PM

The code at the FTP site looks OK.

Yeah, looking through the book online, I'm pretty sure this is PEBCAK.
Was This Post Helpful? 0
  • +
  • -

#14 David W  Icon User is offline

  • DIC supporter
  • member icon

Reputation: 275
  • View blog
  • Posts: 1,764
  • Joined: 20-September 08

Re: Linked lists omissions by author, such as not defining NULL

Posted 08 March 2012 - 07:20 PM

View PostJackOfAllTrades, on 08 March 2012 - 06:44 PM, said:

The code at the FTP site looks OK.

Yeah, looking through the book online, I'm pretty sure this is PEBCAK.


Hey ... just a newbie ... so much to see and digest yet ... no need, yet, to pe... :)

You guys are great with the nudges in the right direction.

This post has been edited by David W: 08 March 2012 - 07:21 PM

Was This Post Helpful? 0
  • +
  • -

#15 mgrex  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 182
  • Joined: 25-March 10

Re: Linked lists omissions by author, such as not defining NULL

Posted 08 March 2012 - 08:01 PM

Thanks, the previous program (17-04)example by the author included const in the function name declaration at the implementation section. I am entering the code as i see it in the textbook. Search for the user Brian Green in the following link: http://www.amazon.co...howViewpoints=1

Since this is the textbook my course uses, I'm trying my best to just to get it over with and get on to a different textbook/guide, ASAP.

In lines 24 and 28 I've changed the constructor/destructor names from NumberList (name of program 17-04) to LinkedList, since this is the name of program 17-05 I'm on, now.

The author later states that takes the header/.cpp file of a program, 3 chapters back, program 14-14, to get Pr17-05 to output the following:

Program Output
Here are the initial values:
5 feet, 4 inches
6 feet, 8 inches
8 feet, 9 inches
Now inserting the value 7 feet 2 inches.
now. Here are the nodes
5 feet, 4 inches
6 feet, 8 inches
7 feet, 2 inches
, feet, 9 inches
Now deleting the last node.
Here are the nodes left.
S feet, 4 inches
6 feet, 8 inches
7 feet, 2 inches

Since #include "FeetInches.h" is included in the intMain file, Pr17-05, I'm guessing we don't need a derive class statement, as depicted in line 22?
Unfortunately he doesn’t show the edits he does to FeetInches, just says that a ‘!=’ overloaded operator needed to be added to it. Line 104 of FeetInches.cpp and Line 59 of FeetInches.h shows the modifications I have done. Line 104 is based on the suggestion of this link, at the bottom of its page: http://courses.cms.c...ie/cpp-ops.html

Unfortunately a compile error results.
I went ahead an added a ‘//’ notation to lines 19 & 20 in FeetInches.h, and the error is far less worse.
When I try to compile the program, an error result. The common one states that in FeetInches.h, lines, 56, 116, & 134, possess and undeclared identifier, ‘num’.
I noticed in the 17-04, the author declared num as argument within the function headers dealing with the linked list, but that program didn’t work with templates, as seen in 17-05 I’m working on now.

Compile error:
 1>------ Build started: Project: 17_05, Configuration: Debug Win32 ------
1>  Pr17-05.cpp
1>c:\path\ch 17\17_05\17_05\linkedlist.h(56): error C2065: 'num' : undeclared identifier
1>          c:\path\ch 17\17_05\17_05\linkedlist.h(49) : while compiling class template member function 'void LinkedList<T>::appendNode(T)'
1>          with
1>          [
1>              T=FeetInches
1>          ]
1>          c:\path\ch 17\17_05\17_05\pr17-05.cpp(10) : see reference to class template instantiation 'LinkedList<T>' being compiled
1>          with
1>          [
1>              T=FeetInches
1>          ]
1>c:\path\ch 17\17_05\17_05\linkedlist.h(116): error C2065: 'num' : undeclared identifier
1>          c:\path\ch 17\17_05\17_05\linkedlist.h(108) : while compiling class template member function 'void LinkedList<T>::insertNode(T)'
1>          with
1>          [
1>              T=FeetInches
1>          ]
1>c:\path\ch 17\17_05\17_05\linkedlist.h(134): error C2065: 'num' : undeclared identifier
1>c:\path\ch 17\17_05\17_05\linkedlist.h(134): fatal error C1903: unable to recover from previous error(s); stopping compilation
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========



LinkedList.h file

 // A class template for holding a linked list. 
//The limitation of the NumberList class is that it can only hold double values.

#ifndef LINKEDLIST_H 
#define LINKEDLIST_H 
#include <iostream> 	// For cout and NULL 
using namespace std; 

template <class T> 
class LinkedList 
{ 
private: 
	// Declare a structure for the list. 
	struct ListNode 
	{ 
		T value;					// The value in this node
		struct ListNode *next;		// To point to the next node 
	}; 

	ListNode *head; // List head pointer 

public: 
	// Constructor : Renamed from NumberList to LinkedList
	LinkedList() 
		{	head = NULL;	} 

	// Destructor : Renamed from NumberList to LinkedList
	~LinkedList();
	//{;}

	// Linked list operations 
	void appendNode(T); 
	void insertNode(T); 
	void deleteNode(T);
	void displayList() const; 
};

// Note that the template uses the ==, !=, and < relational operators to compare node values, 
// and it uses the << (line 93) operator with cout to display node values. Any type passed to  
// the template must support these operators. 


//********************************************************
// appendNode appends a node containing the value 
// passed into newValue, to the end of the list. 
//******************************************************** 
template <class T> 
void LinkedList<T>::appendNode(T newValue) 
{ 
	ListNode *newNode;		// To point to a new node 
	ListNode *nodePtr;		// To move through the list 


	// Allocate a new node and store nurn there. 
	newNode = new ListNode; 
	newNode->value = num; 
	newNode->next = NULL; 

	// If there are no nodes in the list make newNode the 1st node. 
	if(!head) 
		head = newNode; 
	// Otherwise, insert newNode at end.
	else 
	{ 
		// Initialize nodePtr to head of list. 
		nodePtr = head; 
		
		// Find the last node in the list. 
		while (nodePtr->next) 
			nodePtr = nodePtr->next; 
		
		// Insert newNode as the last node. 
		nodePtr->next = newNode; 
	}
}

//************************************************** 
// displayList shows the value 
// stored in each node of the linked list 
// pointed to by head. 
//************************************************** 
template <class T> 
void LinkedList<T>::displayList() const
{ 
	// To move through the list
	ListNode *nodePtr;
	
	// Position nodePtr at the head of the list. 
	nodePtr = head;		

	// While nodeptr points to a node, traverse the list. 
	while (nodePtr)		
	{ 
		// Display the value in this node. 
		cout << nodePtr->value << endl; 

		// Move to the next node. 
		nodePtr = nodePtr->next; 
	}
}

//*****************************************************
// The insertNode function inserts a node with 
// newValue copied to its value member. 
//*****************************************************
template <class T> 
void LinkedList<T>::insertNode(T newValue) 
{
	ListNode *newNode;				// A new node 
	ListNode *nodePtr;				// To traverse the list 
	ListNode *previousNode = NULL;	// The previous node 
	
	
	// Allocate a new node and store num there. 
	newNode = new ListNode; 
	newNode->value = num; 
	
	// If there are no nodes in the list make newNode the first node. 
	if(!head) 
	{ 
		head = newNode; 
		newNode->next = NULL; 
	} 
	// Otherwise, insert newNode. 
	else 
	{ 
		// position nodePtr at the head of list. 
		nodePtr = head; 

		// Initialize previousNode to NULL. 
		previousNode = NULL; 

		// Skip all nodes whose value is less than num. 
		while (nodePtr != NULL && nodePtr->value < num) 
		{ 
			previousNode = nodePtr; 
			nodePtr = nodePtr->next; 
		} 

		// If the new node is to be the 1st in the list, 
		// insert it before all other nodes. 
		if (previousNode == NULL) 
		{
			head = newNode; 
			newNode->next = nodePtr; 
		}

		else // Otherwise insert after the previous node. 
		{ 
			previousNode->next = newNode; 
			newNode->next = nodePtr; 
		} 
	} 
} 

//******************************************************** 
// The deleteNode function searches for a node • 
// with searchValue as its value. The node, if found, * 
// is deleted from the l ist and from memory. * 
//******************************************************** 
template <class T> 
void LinkedList<T>::deleteNode(T searchValue) 
{ 
	ListNode *nodePtr;			// To traverse the list 
	ListNode *previousNode;		// To point to the previous node

	// If the list is empty, do nothing. 
	if (!head) 
		return; 
	// Determine if the first node is the one. 
	if (head->value == num) 
	{ 
		nodePtr = head->next; 
		delete head; 
		head = nodePtr; 
	} 
	else 
	{ 
		// Initialize nodePtr to head of list. 
		nodePtr = head; 

		// Skip a11 nodes whose value member is not equal to num.
		while (nodePtr != NULL && nodeptr->value != num) 
		{ 
			previousNode = nodePtr; 
			nodePtr = nodeptr->next;
		} 

		// If nodePtr is not at the end of the list, link the prevLous
		// node to the node after nodePtr, then delete nodePtr.
		if (nodePtr) 
		{
			previousNode->next = nodePtr->next; 
			delete nodePtr;
		}
	} 
} 




//******************************************************** 
// Destructor 
// This function deletes every node in the list.
//******************************************************** 
template <class T> 
LinkedList<T>::~LinkedList() 
{ 
	ListNode *nodePtr;		// To traverse the list 
	ListNode *nextNode;		// To point to the next node 

	// position nodePtr at the head of the list. 
	nodePtr = head; 

	// While nodePtr is not at the end of the list... 
	while (nodePtr != NULL) 
	{ 
		// Save a pointer to the next node . 
		nextNode = nodePtr->next; 
		// Delete the current node. 
		delete nodePtr; 
		// position nodePtr at the next node . 
		nodePtr = nextNode; 
	} 
}
#endif 
 


FeetInches.h
#ifndef FEETINCHES_H
#define FEETINCHES_H
//#include "LinkedList.h"

#include <iostream>
using namespace std;

//template <class T>
//**********************************************************
// Each time the name LinkedList is used in the class template,
// the type, parameter T is used with it.

// The FeetInches class holds distances or measurements 
// expressed in feet and inches. 

//class FeetInches : public LinkedList<T>;

// Function Prototypes for Overloaded Stream Operators 
//ostream &operator << (ostream &, const FeetInches &); 
//istream &operator >> (istream &, FeetInches &);

class FeetInches //: public LinkedList  // even with '<T>', error persists.
{
private: 
	int feet;			// To hold a number of feet 
	int inches;		// To hold a number of inches 
	void simplify();	// Defined in Feetlnches.cpp 

public: 
	// Constructor: allows the feet and inches members to be set. Default values for these members is 0.
	FeetInches(int f = 0, int i = 0) 
		{	feet = f; 
			inches = i; 
			simplify(); }

	// Mutator functions 
	void setFeet(int f) 
		{	feet = f;	} 

	void setInches(int i) 
		{	inches = i; 
			simplify(); } 

	// Accessor functions 
	int getFeet() const 
		{	return feet;	}

	int getInches() const 
		{	return inches; } 

	// Overloaded operator functions 
	FeetInches operator + (const FeetInches &);	// Overloaded + 
	FeetInches operator - (const FeetInches &);	// Overloaded -
	
	bool operator == (const FeetInches &);  //  Overloaded  == 
	bool operator > (const FeetInches &); // Overloaded	> 
	bool operator < (const FeetInches &); // Overloaded < 
	
	bool operator != (const FeetInches &);		//

//********************************************
	friend ostream &operator << (ostream &strm, const FeetInches &obj) 
	{ 
		strm << obj.feet << " feet, " << obj.inches << " inches"; 
		return strm; 
	}

//************************************************************************************************
//The function returns a reference to an istream object so several of these expressions may be chained together. 
//************************************************************************************************
	friend istream &operator >> (istream &strm, FeetInches &obj) 
	{ 
		// Prompt the user for the feet. 
		cout << "Feet:  "; 
		strm >> obj.feet; 
		// Prompt the user for the inches. 
		cout << "Inches: "; 
		strm >> obj.inches; 
		// Normalize the values. 
		obj.simplify(); 
		return strm; 
	}

//****************************************************************
//function contains an algorithm that will calculate the decimal
//equivalent of a feet and inches measurement.
//E.g. 4 feet 6 inches will be converted to 4.5.
//No return type is specified in the function header, because the
//function is a FeetInches-to-double conversion function, it will
//always return a double. Also, because the function takes no
//arguments, there are no parameters.
//****************************************************************	
	operator double() //changed from FeetInches::operator double(), since definitions are already
	{					//defined inside of the class.
		double temp = feet; 
		temp += (inches / 12.0); 
		return temp; 
	}


//****************************************************************
//An operator function that converts a FeetInches object to an int. 
//This function simply returns the feet member, thus truncating the inches value
//****************************************************************
	operator int() 
	{ 
		return feet; 
	}

};
#endif


FeetInches.cpp
#include <cstdlib>			// Needed  for  abs() 
#include "FeetInches.h" 

//*****************************************************************
//  Definition of member function simplify.  This  function 
//  checks fo  values in the  inches  member  greater  than 
//  12 or  less  than  0.  If  such  a  value  is  found, 
//  the  numbers  in feet  and  inches are adjusted  to  conform 
//  to a standard feet  &  inches  expression. For example, 
//  3 feet 14 inches  would  be  adjusted  to 4 feet 2  inches and   
//  5 feet -2 inches would be adjusted to 4 feet 10  inches.  
//*****************************************************************

void  FeetInches::simplify()	//simplify function is for normalizing the values held in feet and inches. This
{								//function adjusts any set of values where the inches member is > 12 or < 0
	if (inches >= 12)
	{ 
		feet += (inches / 12); 
		inches = inches % 12; 
	}
	else if (inches < 0) 
	{ 
		feet -= ((abs(inches) / 12) + 1);    //abs() function, requires that cstdlib be included. 
		inches = 12 - (abs(inches) % 12);
	}
}

//****************************************** 
// Overloaded binary + operator.
//****************************************** 
FeetInches FeetInches::operator + (const FeetInches &right) 
{ 
	FeetInches  temp;		//this object is a temporary location for holding the results of the addition
 
	temp.inches = inches + right.inches;	//adds inches to right.inches and stores the result to temp.inches
	temp.feet = feet + right.feet;			//adds  feet to  right.  feet and stores the result in temp, feet
	temp.simplify(); 		// adjust the values so they conform to a normal value expressed in feet and inches.
	return temp;			//return the value stored in temp
}

//****************************************** 
// Overloaded binary - operator.
//****************************************** 
FeetInches FeetInches::operator - (const FeetInches &right) 
{ 
	FeetInches temp;  
	temp.inches = inches - right.inches; 
	temp.feet = feet - right.feet; 
	temp.simplify(); 
	return temp;
}

bool FeetInches::operator == (const FeetInches &right) 
{  
	bool status; 

	if (feet == right.feet && inches == right.inches) 
		status = true;
	else 
		status = false;
		
	return status; 
}	
	
bool FeetInches::operator > (const FeetInches &right) 
{  
	bool status; 

	if (feet > right.feet) 
		status = true; 
	else if (feet == right.feet && inches > right.inches) 
		status = true;
	else 
		status = false;
		
	return status; 
}

bool FeetInches::operator < (const FeetInches &right) 
{  
	bool status; 

	if (feet < right.feet) 
		status = true; 
	else if (feet == right.feet && inches < right.inches) 
		status = true;
	else 
		status = false;
		
	return status; 
}

bool FeetInches::operator != (const FeetInches &right) 
{  
	/*bool status;	

	if (feet != right.feet && inches != right.inches) 
		status = true;
	else 
		status = false;
		
	return status; */ 
	//Alternative method according to one site
	return !(*this == right);
}	


////////////////////////////////////////////////

Pr17-05 int main, entered exactly as the author, no syntax error
// This program demonstrates the linked list template. 
#include <iostream> 
#include "LinkedList.h" 
#include "FeetInches.h" 
using namespace std; 

int main() 
{ 
	 // Define a LinkedList object. 
	LinkedList<FeetInches> list;

	// Define some FeetInches objects. 
	FeetInches distance1(5, 4); // 5 feet 4 inches 
	FeetInches distance2(6, 8); // 6 feet 8 inches 
	FeetInches distance3(8, 9); // 8 feet 9 inches 

	// Store the Feetlnches objects in the list. 
	list.appendNode(distance1); // 5 feet 4 inches 
	list.appendNode(distance2); // 6 feet 8 inches 
	list.appendNode(distance3); // a feet 9 inches 

	// Display the values in the list. 
	cout << "Here are the initial values:\n";
	list.displayList(); 
	cout << endl; 

	// Insert another FeetInches object. 
	cout << "Now inserting the value 7 feet 2 inches.\n"; 
	FeetInches distance4(7, 2); 
	list.insertNode(distance4); 
	
	// Display the values in the list. 
	cout << "Here are the Nodes now.\n"; 
	list.displayList(); 
	cout << endl; 

	// Delete the last Node. 
	cout << "Now deleting the last Node. \n"; 
	FeetInches distance5(8, 9); 
	list.deleteNode(distance5); 
	// Display the values in the list. 
	cout << "Here are the Nodes left.\n"; 
	list.displayList(); 
	
	system("pause");
	return 0; 
} 

This post has been edited by mgrex: 08 March 2012 - 09:17 PM

Was This Post Helpful? 0
  • +
  • -

  • (3 Pages)
  • +
  • 1
  • 2
  • 3