Reverse the elements of Java LinkedList - Walking Techie

Blog about Java programming, Design Pattern, and Data Structure.

Friday, December 2, 2016

Reverse the elements of Java LinkedList

LinkedList is doubly-linked list implementation of the List and Deque interfaces.

How to reverse elements of Java LinkedList?

This example gives how to reverse elements in the LinkedList. You can reverse the content of Java ArrayList by calling Collections.reverse() method. Collections.reverse(list). Reverse the order of the elements in the specified list.

package com.walking.techie;

import java.util.Collections;
import java.util.LinkedList;

public class LinkedListReverseDemo {

 public static void main(String[] args) {
  LinkedList<String> language = new LinkedList<String>();
  language.add("C");
  language.add("CPP");
  language.add("JAVA");
  language.add("DOTNET");
  language.add("C#");
  language.add("PHP");

  System.out.println("Original language linked list " + language);
  // reverse a linked list
  Collections.reverse(language);

  System.out.println("language linked list after reverse applied " + language);
 }
}

Output of above program is shown below:

Original language linked list [C, CPP, JAVA, DOTNET, C#, PHP]
language linked list after reverse applied [PHP, C#, DOTNET, JAVA, CPP, C]

No comments :

Post a Comment