阅读 37

【学习笔记】Core Java - 9.3.1 LinkedList

In the Java programming language, all linked lists are actually doubly linked.

Iterator

import java.util.*;

public class LinkedListTest
{
   public static void main(String[] args)
   {
      var staff = new LinkedList<String>(); 
      staff.add("Amy"); 
      staff.add("Bob"); 
      staff.add("Carl"); 
      Iterator<String> iter = staff.iterator(); 
      String temp = iter.next();   // 返回第一个元素
      System.out.println(temp);    // Amy
      temp = iter.next(); 
      System.out.println(temp);    // Bob
      iter.remove(); 
      
      System.out.println(staff);   // [Amy, Carl]
   }
}
复制代码

ListIterator

当我们需要在一个linked list中间插入或者删除元素的时候,需要用到listIterator方法

  • The add method adds the new element before the iterator position.
  • If the linked list has n elements, there are n + 1 spots for adding a new element.
import java.util.*;
/**
 * This program demonstrates operations on linked lists.
 * @version 1.12 2018-04-10
 * @author Cay Horstmann
 */
public class LinkedListTest
{
   public static void main(String[] args)
   {
      var a = new LinkedList<String>();
      a.add("Amy");
      a.add("Carl");
      a.add("Erica");

      var 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())
      {
         String temp = bIter.next(); // skip one element
         System.out.println(temp); 
         if (bIter.hasNext())
         {
            bIter.next(); // skip next element
            bIter.remove(); // remove that element
         }
      }

      System.out.println(b);      // [Bob, Frances]

      // bulk operation: remove all words in b from a
      a.removeAll(b);
      System.out.println(a);     // [Amy, Carl, Doug, Erica, Gloria]
   }
}
复制代码
文章分类
后端
文章标签