我需要理解简单的例子
LinkedList list = new LinkedList();
list.add("J");
list.add("A");
list.add("V");
list.add("A");
我有简单的LinkedList,需要将它传递给方法反向
public void reverse(LinkedList list) {
}
将返回反向新列表
我不需要任何ArraysUtils来反转它
反转输出的简短和实践方法是什么?
同样需要理解简单数组。
答案 0 :(得分:5)
答案 1 :(得分: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;
}
答案 2 :(得分:1)
集合类的反向方法是我猜你需要的。您可以根据需要更改实施
/**
* 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);
}
}
}
答案 3 :(得分:1)
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(..,..)
方法先前返回指定位置的元素
答案 4 :(得分: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;
}