/* * Copyright (C) 2009 E.Albert, P.Arenas, S.Genaim, G.Puebla, and D.Zanardini * https://costa.ls.fi.upm.es * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package pubs; /** * This class implements a method for copying linked lists. * * * @author M. Zamalloa * */ class Cons extends LinkedList { int elem; LinkedList next; LinkedList copy(){ Cons res = new Cons(); res.elem = this.elem; if (this.next != null) res.next = this.next.copy(); else res.next = null; return res; } public static void main(String[] args) { // Prepare the test with 10 elements Cons test = new Cons(); test.elem = 0; test.next = null; Cons tail = test; int i = 0; while (i < 9) { Cons aux = new Cons(); aux.elem = i; aux.next = null; tail.next = (Cons)aux; tail = (Cons)tail.next; i++; } // Start first test Cons result = (Cons)test.copy(); tail = test; System.out.println("Result: "); /* // Prepare the test with 50 elements test = new Cons(); test.elem = 0; test.next = null; tail = test; i = 0; while (i < 49) { Cons aux = new Cons(); aux.elem = i; aux.next = null; tail.next = (Cons)aux; tail = (Cons)tail.next; i++; } // Start second test result = (Cons)test.copy(); tail = test; System.out.println("Result: "); while (tail != null) { System.out.println(tail.elem+" "); tail = (Cons)tail.next; } // Prepare the test with 100 elements test = new Cons(); test.elem = 0; test.next = null; tail = test; i = 0; while (i < 99) { Cons aux = new Cons(); aux.elem = i; aux.next = null; tail.next = (Cons)aux; tail = (Cons)tail.next; i++; } // Start the third test result = (Cons)test.copy(); tail = test; System.out.println("Result: "); while (tail != null) { System.out.println(tail.elem+" "); tail = (Cons)tail.next; }*/ } }