现在的位置: 首页 > 综合 > 正文

List.h

2011年08月01日 ⁄ 综合 ⁄ 共 2247字 ⁄ 字号 评论关闭
1 #include<iostream>
2  using namespace std;
3 const int max_list = 2001;
4 enum Error_code
5 {
6 success, fail, rang_error, underflow, overflow, not_present
7 };
8
9 template <class List_entry>
10 class List
11 {
12 public:
13 List();
14 virtual ~List();
15 int size() const;
16 bool full() const;
17 bool empty() const;
18 void clear();
19 void traverse(void (*visit)(List_entry &));
20 Error_code retrieve(int position, List_entry &x) const;
21 Error_code replace(int position, const List_entry &x);
22 Error_code remove(int position, List_entry &x);
23 Error_code insert(int position, const List_entry &x);
24 protected:
25 int count;
26 List_entry entry[max_list];
27 };
28
29 template <class List_entry>
30 List<List_entry>::List()
31 {
32 count = 0;
33 }
34
35 template <clast List_entry>
36 List<List_entry>::~List()
37 {
38 count = 0;
39 }
40
41 template <clast List_entry>
42 int List<List_entry>::size() const
43 {
44 return count;
45 }
46
47 template <clast List_entry>
48 bool List<List_entry>::full() const
49 {
50 if (count > max_list)
51 return 1;
52 else
53 return 0;
54 }
55
56 template <clast List_entry>
57 bool List<List_entry>::empty() const
58 {
59 if (count <= 0)
60 return 1;
61 else
62 return 0;
63 }
64
65 template <clast List_entry>
66 void List<List_entry>::clear()
67 {
68 count = 0;
69 }
70
71 template <class List_entry>
72 void List<List_entry>::traverse(void (*visit)(List_entry &))
73 {
74 int i;
75 for (i = 0; i < count; i++)
76 {
77 (*visit)(entry[i]);
78 }
79 }
80
81 template <class List_entry>
82 Error_code List<List_entry>::retrieve(int position, List_entry &x) const
83 {
84 if (position < 0 || position >= count )
85 return rang_error;
86 x = entry[position];
87 return success;
88 }
89
90 template <class List_entry>
91 Error_code List<List_entry>::replace(int position, const List_entry &x)
92 {
93 if (position < 0 || position >= count)
94 return rang_error;
95 entry[position] = x;
96 return success;
97 }
98
99 template <class List_entry>
100 Error_code List<List_entry>::remove(int position, List_entry &x)
101 {
102 if (empty())
103 return underflow;
104 if (position < 0 || position >= count)
105 return rang_error;
106 for (int i = position; i < count; i++)
107 {
108 entry[i] = entry[i+1]
109 }
110 x = entry[position];
111 count--;
112 return success;
113 }
114
115 template <class List_entry>
116 Error_code List<List_entry>::insert(int position, const List_entry &x)
117 {
118 if (full())
119 return overflow;
120 if (position < 0 || position > count)
121 return rang_error;
122
123 for (int i = count - 1; i >= position; i--)
124 {
125 entry[i+1] = entry[i];
126 }
127 entry[position] = x;
128 count++;
129 return success;
130 }

抱歉!评论已关闭.