3

我需要理解简单的例子

 LinkedList list = new LinkedList();
        list.add("J");
        list.add("A");
        list.add("V");
        list.add("A");

我有简单的 LinkedList,需要将它传递给方法 reverse

public void reverse(LinkedList list) {

}

这将返回反向的新列表

我不需要任何 ArraysUtils 来反转它

反向输出的简短实用方法是什么。

对于简单的数组,同样需要理解。

4

5 回答 5

6

You can use the Collections class.

Collections.reverse(list);

Your list will be reversed after that operation.

于 2013-05-15T07:45:10.263 回答
3
public void reverse(LinkedList list) {
    //run till middle and swap start element with end element and so on
    for(int i = 0, mid = list.size()/2, j = list.size() - 1; i < mid; i++, j--)
        list.set(i, list.set(j, list.get(i)));//swap
}

注意:List.set(..,..)方法返回之前指定位置的元素

于 2013-05-15T07:58:26.270 回答
1

尝试这个。

public LinkedList<String> reverse(LinkedList list) {
LinkedList reverseList=null;

for(int i=list.size();i>0;i--)
{
reverseList.add(list.get(i))
}
return reverseList;
}
于 2013-05-15T07:48:25.307 回答
1

我猜你需要 Collections 类的 reverse 方法。您可以根据需要更改实现

/**
 * Reverses the order of the elements in the specified list.<p>
 *
 * This method runs in linear time.
 *
 * @param  list the list whose elements are to be reversed.
 * @throws UnsupportedOperationException if the specified list or
 *         its list-iterator does not support the <tt>set</tt> operation.
 */
public static void reverse(List<?> list) {
    int size = list.size();
    if (size < REVERSE_THRESHOLD || list instanceof RandomAccess) {
        for (int i=0, mid=size>>1, j=size-1; i<mid; i++, j--)
            swap(list, i, j);
    } else {
        ListIterator fwd = list.listIterator();
        ListIterator rev = list.listIterator(size);
        for (int i=0, mid=list.size()>>1; i<mid; i++) {
    Object tmp = fwd.next();
            fwd.set(rev.previous());
            rev.set(tmp);
        }
    }
}
于 2013-05-15T07:51:23.720 回答
1
public ListNode reverseList(ListNode head) {
    if(head == null) return head;

    Stack<ListNode> stack = new Stack<ListNode>();
    while(head != null) {
        stack.push(head);
        head = head.next;
    }

    ListNode dummy = new ListNode(0);
    head = dummy;
    while(!stack.isEmpty()) {
        ListNode current = stack.pop();
        head.next = new ListNode(current.val);
        head = head.next;
    }

    return dummy.next;
}
于 2019-09-14T12:16:51.200 回答