Mega Code Archive

 
Categories / Java / Collections Data Structure
 

This program demonstrates operations on linked lists

/*    This program is a part of the companion code for Core Java 8th ed.    (http://horstmann.com/corejava)    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/>. */ import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; /**  * This program demonstrates operations on linked lists.  * @version 1.10 2004-08-02  * @author Cay Horstmann  */ public class LinkedListTest {    public static void main(String[] args)    {       List<String> a = new LinkedList<String>();       a.add("Amy");       a.add("Carl");       a.add("Erica");       List<String> b = new LinkedList<String>();       b.add("Bob");       b.add("Doug");       b.add("Frances");       b.add("Gloria");       // merge the words from b into a       ListIterator<String> aIter = a.listIterator();       Iterator<String> bIter = b.iterator();       while (bIter.hasNext())       {          if (aIter.hasNext()) aIter.next();          aIter.add(bIter.next());       }       System.out.println(a);       // remove every second word from b       bIter = b.iterator();       while (bIter.hasNext())       {          bIter.next(); // skip one element          if (bIter.hasNext())          {             bIter.next(); // skip next element             bIter.remove(); // remove that element          }       }       System.out.println(b);       // bulk operation: remove all words in b from a       a.removeAll(b);       System.out.println(a);    } }