2010-05-15 218 views
6

Deseo mantener el orden de los elementos que se agregan en una lista. Entonces, usé un LinkedList en Java.Intercambiar elementos en LinkedList

Ahora quiero ser capaz de intercambiar dos elementos en la lista vinculada. Antes que nada, no puedo encontrar un elementAt() para LinkedList. Además, no hay forma de agregar elemento en una posición específica.

Respuesta

2

Mira la Javadocs para LinkedList

Para encontrar un elemento a una index uso get(int index)

Para hacer un element en un determinado index use set(int index, Object element)

0

Eche un vistazo a ArrayList, esta clase mantendrá el orden de inserción y proporcionará O (1) acceso aleatorio.

2

Si está escribiendo su propia clase LinkedList para el ejercicio (es decir, para un proyecto o una escuela), intente hacer dos variables de objeto temporales y dos ints para mantener su posición en la lista. Luego, use add (int, Object) para agregar el primero en la 2 ° posición, el segundo en la 1 ° posición.

0
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; 
    } 
} 

}

Cuestiones relacionadas