fork(6) download
  1. import java.util.LinkedList;
  2. import java.util.ListIterator;
  3.  
  4. public class Main {
  5. public static void main(String[] args) {
  6. final LinkedList<String> list = new LinkedList<String> ();
  7.  
  8. list.add ("1"); list.add ("2"); list.add ("3"); list.add ("4");
  9.  
  10. final MyIterator<String> it = new MyIterator (list.listIterator());
  11.  
  12. System.out.println(it.next());
  13. System.out.println(it.next ());
  14. System.out.println(it.next ());
  15. System.out.println(it.previous ());
  16. System.out.println(it.previous ());
  17. System.out.println(it.next ());
  18. }
  19.  
  20. public static class MyIterator<T> {
  21.  
  22. private final ListIterator<T> listIterator;
  23.  
  24. private boolean nextWasCalled = false;
  25. private boolean previousWasCalled = false;
  26.  
  27. public MyIterator(ListIterator<T> listIterator) {
  28. this.listIterator = listIterator;
  29. }
  30.  
  31. public T next() {
  32. nextWasCalled = true;
  33. if (previousWasCalled) {
  34. previousWasCalled = false;
  35. listIterator.next ();
  36. }
  37. return listIterator.next ();
  38. }
  39.  
  40. public T previous() {
  41. if (nextWasCalled) {
  42. listIterator.previous();
  43. nextWasCalled = false;
  44. }
  45. previousWasCalled = true;
  46. return listIterator.previous();
  47. }
  48.  
  49. }
  50. }
  51.  
Success #stdin #stdout 0.07s 215552KB
stdin
Standard input is empty
stdout
1
2
3
2
1
2