A Look at Linked Lists 877
E
LISTINGE.1 Linked List
1: // ***********************************************
2: // FILE: Listing E.1
3: // PURPOSE: Demonstrate a linked list
4: // NOTES:
5: //
6: // COPYRIGHT: Copyright (C) 2000-04 Liberty Associates, Inc.
7: // All Rights Reserved
8: //
9: // Demonstrates an object-oriented approach to
10: // linked lists. The list delegates to the node.
11: // The node is an abstract data type. Three types of
12: // nodes are used, head nodes, tail nodes and internal
13: // nodes. Only the internal nodes hold data.
14: //
15: // The Data class is created to serve as an object to
16: // hold in the linked list.
17: //
18: // ***********************************************
19:
20:
21: #include <iostream>
22: using namespace std;
23:
24: enum { kIsSmaller, kIsLarger, kIsSame};
25:
26: // Data class to put into the linked list
27: // Any class in this linked list must support two methods:
28: // Show (displays the value) and
29: // Compare (returns relative position)
30: class Data
31: {
32: public:
33: Data(int val):myValue(val){}
34: ~Data(){}
35: int Compare(const Data &);
36: void Show() { cout << myValue << endl; }
37: private:
38: int myValue;
39: };
40:
41: // Compare is used to decide where in the list
42: // a particular object belongs.
43: int Data::Compare(const Data & theOtherData)
44: {
45: if (myValue < theOtherData.myValue)
46: return kIsSmaller;
47: if (myValue > theOtherData.myValue)
48: return kIsLarger;
33 0672327112_app_e.qxd 11/19/04 12:30 PM Page 877