CodesJava

Easy learning with example program codes

how to swap two elements in a linked list java?


LinkedList:

The LinkedList class extends AbstractSequentialList and implements the List and Deque interface. It uses linked list data structure to store elements. It can contain duplicate elements. It is not synchronized.

Note: It not provides the random access facility.

We can use Collections.swap() method to swap two elements in a linked list in java. We have to pass the indexes which you need to swap.

Example:

package com.codesjava;
 
import java.util.Collections;
import java.util.LinkedList;
 
public class Test {
  public static void main(String args[]){
	LinkedList<String> linkedList = new LinkedList<String>();
	linkedList.add("Jai");
	linkedList.add("Mahesh");
	linkedList.add("Naren");
	linkedList.add("Vivek");
	linkedList.add("Vishal");
	linkedList.add("Hemant");
	System.out.println("Actual LinkedList:"+linkedList);
	Collections.swap(linkedList, 2, 4);
        System.out.println("Results after swap operation:" + linkedList);
  }
}

Output

Actual LinkedList:[Jai, Mahesh, Naren, Vivek, Vishal, Hemant]
Results after swap operation:[Jai, Mahesh, Vishal, Vivek, Naren, Hemant]
Sign Up/ Sign In
Ask a Question


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki