LinkedList Swap Elements

I want to keep the order of the items added to the list. So, I used LinkedList in Java.

Now I want to be able to exchange two items in a linked list. First of all, I cannot find elementAt() for LinkedList . In addition, there is no way to add an item to the specified position.

+6
java linked-list swap
source share
6 answers

There is Collections.swap(List<?> list, int i, int j) , which can be used to replace two List<?> Elements. There are also LinkedList.get(int index) and LinkedList.add(int index, E element) (both methods specified by interface List ). All of these operations will be O(N) , since a LinkedList does not implements RandomAccess .

+22
source share

Check out Javadocs on LinkedList

To find an element in index , use get(int index)

To place element at some index , use set(int index, Object element)

+2
source share

If you are writing your own LinkedList class for exercises (i.e. for a project or school), try making two temporary Object variables and two ints to keep your position in the list. Then use add (int, Object) to add the first to the 2nd position, the second to the 1st position.

+2
source share

add

Is this what you want?

If you want to keep the list in sorted state, why not just insert an element using addfirst

and then sort the list using Collections.sort

0
source share

Take a look at ArrayList , this class will support insertion order and provide O (1) random access.

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

}

0
source share

All Articles