Reverse a LinkedList - Walking Techie

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

Friday, December 2, 2016

Reverse a LinkedList

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

How to reverse content of Java LinkedList?

Here we will see an example for reversing the content of the Java LinkedList. You can reverse the content of linked list by calling Collections.reverse(list) method, need to pass the instance of List interface to this method.

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