/**
190 * Make the current list a copy of another list.
191 * Performs a deep copy, that is it makes a new copies of each of
8
Data Structures and Team Project Answers – Lists
192 * the DataElements within the other list.
193 *
194 * @param otherList the LinkedListClass to duplicate.
195 */
196
197 private void copy(LinkedListClassEx3 otherList) {
198 LinkedListNode newNode; // variable to create a node
199 LinkedListNode current; // variable to traverse the list
200
201 first = null; //make this list empty
202
203 if ( otherList.first == null ) {
204 // otherList is empty
205 first = null;
206 last = null;
207 count = 0;
208 } else {
209 // Copy other list into this list
210 // Start with the first element of the other list
211 count = otherList.count;
212 current = otherList.first;
213
214 // Copy the first element
215 first = new LinkedListNode();
216 first.data = current.data.getCopy();
217 first.link = null;
218
219 // We now have one node in out list
220 last = first;
221
222 // Start to traverse the other list
223 current = current.link;
224
225 // While there are nodes in the other list,
226 // copy them into this list
227 while ( current != null ) {
228 // Make copy of node in other list
229 newNode = new LinkedListNode();
230 newNode.data = current.data.getCopy();
231
232 // Add new node to end of this list
233 newNode.link = null;
234 last.link = newNode;
235 last = newNode;
236
237 // Move on to next node in other list
238 current = current.link;
239 }
240 }
241 }
242
243 /**
244 * Make this list a copy of another list.
245 * This is simply another name for the copy() method.
246 *
247 * @param otherList the other LinkedListClass to duplicate.
248 */
249
250 public void copyList(LinkedListClassEx3 otherList) {
251 if ( this != otherList ) {
252 //avoid self-copy
253 copy(otherList);
254 }
255 }
256
257 /**
9
Data Structures and Team Project Answers – Lists
258 * Copy constructor, makes a new list which is a direct copy
259 * of another list. This list is a deep copy of the other
260 * list.
261 *
262 * @param otherList the other LinkedListClass to copy.
263 */
264
265 public LinkedListClassEx3(LinkedListClassEx3 otherList) {
266 copy(otherList);
267 }
268 }