문제

I am trying to create a linkedlist with 20 objects in it and then iterate forward through it and then backwards but I cannot figure out how to move backwards through the list, there is not a built in method in the LinkedList class.

I was also wondering if there was a way to randomly generate first and last names.

Here is the class

import javax.swing.JOptionPane;
import java.util.*;

public class Class {


    public static void main(String[] args) {


        LinkedList roster = new LinkedList();

        for(int i=0; i<2; i++){
           Student stu = new Student();
           stu.id = i;
           stu.populateName(JOptionPane.showInputDialog("Please enter a first name"), JOptionPane.showInputDialog("Please enter a last name"));
           roster.add(stu);


    }
        Iterator<Student> it=roster.iterator();
            while (it.hasNext()) {

            Student st=it.next();
            JOptionPane.showMessageDialog(null, st.firstName + " " + st.lastName);
            }




    } 
}
도움이 되었습니까?

해결책

You can use LinkedList.descendingIterator() (which is there since Java 1.6)

here's the javadoc

Returns an iterator over the elements in this deque in reverse sequential order. The elements will be returned in order from last (tail) to first (head).

Usage

    LinkedList<Integer> ll = new LinkedList<Integer>();
    ll.add(1);
    ll.add(2);
    ll.add(3);

    System.out.println("Normal traversal");
    for(Iterator<Integer> i = ll.iterator(); i.hasNext();) {
        System.out.println(i.next());
    }
    System.out.println("Reverse");
    for(Iterator<Integer> i = ll.descendingIterator(); i.hasNext();) {
        System.out.println(i.next());
    }

There is one more way of doing this using LinkedList.listIterator(index) method too

    ListIterator<Integer> i = ll.listIterator(ll.size()); //creates a ListIterator with starting index as the size of LinkedList, to point to the last element
    while(i.hasPrevious()) {
        System.out.println(i.previous());
    }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top