Write a program to reverse items in a LinkedList in Java

Below program illustrates how to reverse items in LinkedList using Java:

public class LinkedListReverse {
 
	public static void main(String[] args) {
		LinkedList list = new LinkedList();
		list.insert(1);
		list.insert(2);
		list.insert(3);
		list.reverse();
		list.print();
	}
}
 
class LinkedList {
 
	private Node head;
	
	public LinkedList() {
 
	}
 
	class Node {
		Object data;
		Node next;
 
		public Node(Object data) {
			this.data = data;
			this.next = null;
		}
	}
 
	/**
	 * Insert operation in LinkedList
	 * 
	 * @param obj
	 * @return
	 */
	public LinkedList insert(Object obj) {
		Node node = new Node(obj);
 
		if (head == null) {
			head = node;
		} else {
			Node current = head;
			while (current.next != null) {
				current = current.next;
			}
			current.next = node;
		}
		return this;
	}
 
	/**
	 * Remove operation in LinkedList
	 * 
	 * @param obj
	 * @return
	 */
	public LinkedList remove(Object obj) {
		if (head == null) {
			return this;
		} else {
			if (obj.equals(head.data)) {
				Node node = head.next;
				head = node;
				return this;
			}
 
			Node node = head;
			Node prev = head;
 
			while (node != null) {
				Node nextNode = node.next;
				if (obj == node.data) {
					prev.next = nextNode;
					System.out.println("Removed an item!");
				}
				prev = node;
				node = nextNode;
			}
		}
		return this;
	}
 
	/**
	 * Print operation in LinkedList
	 */
	public void print() {
		Node node = this.head;
		while (node != null) {
			System.out.print(node.data + "->");
			node = node.next;
		}
		System.out.println("NULL");
	}
 
	/**
	 * Performs reverse operation on LinkedList
	 * 
	 * @return
	 */
	public LinkedList reverse() {
		Node prev = null;
		Node current = head;
 
		while (current != null) {
			Node next = current.next;
			current.next = prev;
			prev = current;
			current = next;
		}
 
		head = prev;
 
		return this;
	}
}

Author: Mahesh

Technical Lead with 10 plus years of experience in developing web applications using Java/J2EE and web technologies. Strong in design and integration problem solving skills. Ability to learn, unlearn and relearn with strong written and verbal communications.