[英]Reverse LinkedList in java
我需要了解簡單的例子
LinkedList list = new LinkedList();
list.add("J");
list.add("A");
list.add("V");
list.add("A");
我有簡單的LinkedList,需要將其傳遞給方法反向
public void reverse(LinkedList list) {
}
這將返回反向的新列表
而且我不需要任何ArraysUtils來反轉它
反轉輸出的簡短實踐方法是什么?
對於簡單數組,同樣需要了解。
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(..,..)
方法將返回先前位於指定位置的元素
嘗試這個。
public LinkedList<String> reverse(LinkedList list) {
LinkedList reverseList=null;
for(int i=list.size();i>0;i--)
{
reverseList.add(list.get(i))
}
return reverseList;
}
我想,Collections類的反向方法是您需要的。 您可以根據需要更改實現
/**
* 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);
}
}
}
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.