2010-05-15 160 views
6

我想維護列表中添加的元素的順序。所以,我在Java中使用了一個LinkedList鏈接列表中的交換元素

現在我想能夠交換鏈接列表中的兩個元素。首先,我找不到一個elementAt()LinkedList。而且,沒有辦法在指定的位置添加元素。

回答

2

退房的Javadoc名單LinkedList

要在index處使用get(int index)

element置於某個index使用set(int index, Object element)

0

看看ArrayList,這個類將保持插入順序並提供O(1)隨機訪問。

2

如果你正在寫的鍛鍊自己的LinkedList類(即一個項目或學校),嘗試使兩個臨時對象變量和兩個整數保持它們在列表中的位置。然後,使用add(int,Object)將第一個添加到第二個位置,將第二個添加到第一個位置。

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

}