[英]Swap elements in LinkedList
我想保持添加到列表中的元素的順序。 所以,我在 Java 中使用了LinkedList
。
現在我希望能夠交換鏈表中的兩個元素。 首先,我找不到LinkedList
的elementAt()
。 此外,無法在指定位置添加元素。
有一個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
。
如果您正在編寫自己的 LinkedList 類用於練習(即用於項目或學校),請嘗試創建兩個臨時 Object 變量和兩個 int 以保持它們在 List 中的位置。 然后,使用 add(int, Object) 在第二個位置添加第一個,在第一個位置添加第二個。
查看LinkedList的 Javadocs
要在index
處查找元素,請使用get(int index)
要將element
放置在某個index
使用set(int index, Object element)
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;
}
}
}
看看ArrayList ,這個類將保持插入順序並提供 O(1) 隨機訪問。
// I tried to reduce time complexity here, in 3 while loops (get() and set() use 4 while loop)
void swapAt(int index1, int index2){ // swapping at index
Node tmp = head;
int count=0;
int min, max; // for future reference to reduce time complexity
if(index1<index2){
min = index1;
max = index2;
}
else{
min = index2;
max = index1;
}
int diff = max - min;
while(min!=count){
tmp= tmp.next;
count++;
}
int minValue = tmp.data;
while(max!=count){
tmp= tmp.next;
count++;
}
int maxValue = tmp.data;
tmp.data = minValue;
tmp = head;
count =0;
while(min!=count){
tmp= tmp.next;
count++;
}
tmp.data = maxValue;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.