我想維護列表中添加的元素的順序。所以,我在Java中使用了一個LinkedList
。鏈接列表中的交換元素
現在我想能夠交換鏈接列表中的兩個元素。首先,我找不到一個elementAt()
的LinkedList
。而且,沒有辦法在指定的位置添加元素。
我想維護列表中添加的元素的順序。所以,我在Java中使用了一個LinkedList
。鏈接列表中的交換元素
現在我想能夠交換鏈接列表中的兩個元素。首先,我找不到一個elementAt()
的LinkedList
。而且,沒有辦法在指定的位置添加元素。
有一個Collections.swap(List<?> list, int i, int j)
,你可以用它來交換一個List<?>
的兩個元素。還有LinkedList.get(int index)
和LinkedList.add(int index, E element)
(都是由interface List
指定的方法)。所有這些操作將爲O(N)
,因爲LinkedList
不是implements RandomAccess
。
看看ArrayList,這個類將保持插入順序並提供O(1)隨機訪問。
如果你正在寫的鍛鍊自己的LinkedList類(即一個項目或學校),嘗試使兩個臨時對象變量和兩個整數保持它們在列表中的位置。然後,使用add(int,Object)將第一個添加到第二個位置,將第二個添加到第一個位置。
public class SwapNode {
public static Node head;
public static void main(String[] args) {
SwapNode obj = new SwapNode();
obj.insertAtEnd(5);
obj.insertAtEnd(6);
obj.insertAtEnd(4);
obj.insertAtEnd(7);
obj.insertAtEnd(3);
obj.insertAtEnd(8);
obj.insertAtEnd(2);
obj.insertAtEnd(9);
obj.insertAtEnd(1);
obj.print(head);
System.out.println("*** Swapped ***");
obj.swapElementValue(4, 2);
}
public void swapElementValue(int value1, int value2) {
if (value1 == value2) {
System.out.println("Values same, so no need to swap");
return;
}
boolean found1 = false, found2 = false;
Node node = head;
while (node != null && !(found1 && found2)) {
if (node.data == value1) {
node.data = value2;
found1 = true;
node = node.next;
continue;
}
if (node.data == value2) {
node.data = value1;
found2 = true;
node = node.next;
continue;
}
node = node.next;
}
if (found1 && found2) {
print(head);
} else {
System.out.println("Values not found");
}
}
public void insertAtEnd(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
return;
}
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = newNode;
}
public void print(Node head) {
Node temp = head;
while(temp != null) {
System.out.print(temp.data);
temp = temp.next;
}
System.out.println();
}
static class Node {
private int data;
public Node next;
public Node(int data) {
this.data = data;
}
}
}
1對於指出的操作取O(N)。 – helpermethod 2010-05-15 08:29:29