简体   繁体   English

交换 LinkedList 中的元素

[英]Swap elements in LinkedList

I want to maintain order of the elements being added in a list.我想保持添加到列表中的元素的顺序。 So, I used a LinkedList in Java.所以,我在 Java 中使用了LinkedList

Now I want to be able to swap two elements in the linked list.现在我希望能够交换链表中的两个元素。 First of all, I cannot find an elementAt() for LinkedList .首先,我找不到LinkedListelementAt() Also, there is no way to add element at a specified position.此外,无法在指定位置添加元素。

There is a Collections.swap(List<?> list, int i, int j) that you can use to swap two elements of a List<?> .有一个Collections.swap(List<?> list, int i, int j)可以用来交换List<?>两个元素。 There's also LinkedList.get(int index) and LinkedList.add(int index, E element) (both are methods specified byinterface List ).还有LinkedList.get(int index)LinkedList.add(int index, E element) (都是interface List指定的方法)。 All of these operations will be O(N) since a LinkedList does not implements RandomAccess .所有这些操作都是O(N)因为LinkedList没有implements RandomAccess

If you are writing your own LinkedList class for exercise (ie for a project or school), try making two temporary Object variables and two ints to hold their position in the List.如果您正在编写自己的 LinkedList 类用于练习(即用于项目或学校),请尝试创建两个临时 Object 变量和两个 int 以保持它们在 List 中的位置。 Then, use add(int, Object) to add the first in the 2nd position, second in the 1st position.然后,使用 add(int, Object) 在第二个位置添加第一个,在第一个位置添加第二个。

Check out the Javadocs for LinkedList查看LinkedList的 Javadocs

To find an element at an index use get(int index)要在index处查找元素,请使用get(int index)

To place an element at a certain index use set(int index, Object element)要将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;
    }
}

} }

add 添加

Does this what you want?这是你想要的吗?

If you want to keep the list in a sorted state, why not just insert the element with addfirst如果你想保持列表处于排序状态,为什么不直接用addfirst插入元素

and then sort the list using Collections.sort然后使用Collections.sort对列表进行排序

看看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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM