リストに追加される要素の順序を維持したい。そこで、LinkedList
Javaでを使用しました。
ここで、リンクリスト内の2つの要素を交換できるようにしたいと思います。まず、elementAt()
forが見つかりませんLinkedList
。また、指定した位置に要素を追加する方法はありません。
リストに追加される要素の順序を維持したい。そこで、LinkedList
Javaでを使用しました。
ここで、リンクリスト内の2つの要素を交換できるようにしたいと思います。まず、elementAt()
forが見つかりませんLinkedList
。また、指定した位置に要素を追加する方法はありません。
Collections.swap(List<?> list, int i, int j)
の2つの要素を交換するために使用できるがありますList<?>
。ともLinkedList.get(int index)
ありLinkedList.add(int index, E element)
ます(どちらもで指定されたメソッドinterface List
です)。これらの操作はすべてO(N)
、aでLinkedList
はないためimplements RandomAccess
です。
演習用に(つまり、プロジェクトまたは学校用に)独自のLinkedListクラスを作成している場合は、2つの一時オブジェクト変数と2つのintを作成して、リスト内での位置を保持してみてください。次に、add(int、Object)を使用して、最初の位置を2番目の位置に追加し、2番目の位置を1番目の位置に追加します。
LinkedListのJavadocを確認してください
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;
}