How to reverse a Singly Linked List iteratively and recursively

Linked List is a data structure that possess following properties:

  • The are a group of nodes linked together by some reference. Singly linked list has reference to next node, while doubly linked list has reference to previous and next nodes.
  • Elements can be inserted indefinitely.
  • They don’t take contiguous memory locations. For this reason, they are suitable to be used even if the disk or memory is fragmented.
  • They allow sequential access to elements while arrays allow random access
  • Extra space is needed for reference. It is impractical to use for boolean or char for space wastage.

Singly linked list might not be a right data structure for all situations, so a care must be taken in choosing the data structure for your problem. As the link in the singly linked list only points to the location of the next object (and not in reverser order), singly linked list can only be traversed in forward direction. Also, you need to know the location of the first node or object to be able to traverser rest of the nodes or objects.

In this article,  I have provided solutions coding for the following:

  • Reversing a singly linked list by using recursion – Recursive Reverse
  • Reversing a singly linked list by using iteration – Iterative Reverse.

Java Implementation Code:

package com.icodejava.blog.datastructure;

/**
 * @author Kushal Paudyal
 * www.icodejava.com
 * Created On -  Feb 28, 2014
 * Last Modified On - Feb 28, 2014
 */
public class LinkedListReverse {
	
	public static void main(String args[]) {
		
		//Preparing some linked list structure
		LinkedList linkedList = new LinkedList(5);
		linkedList.next = new LinkedList(4);
		linkedList.next.next = new LinkedList(3);
		linkedList.next.next.next = new LinkedList(2);
		linkedList.next.next.next.next = new LinkedList(1);

		System.out.println("Original Linked List: " + linkedList.toString());

		//recursively reverse and print
		linkedList = recursiveReverse(linkedList);
		System.out.println("Recursively Reversed List: "
				+ linkedList.toString());

		//iteratively reverse and print
		linkedList = iterativeReverse(linkedList);
		System.out.println("Iteratively Recursed to Original: "
				+ linkedList.toString());
	}

	/**
	 * This method uses recursive method to reverse a singly linked list.
	 */
	public static LinkedList recursiveReverse(LinkedList linkedList) {

		// check for empty or size 1 linked list. This is a base condition to
		// terminate recursion.
		if (linkedList == null || linkedList.next == null) {
			return linkedList;
		}

		LinkedList remainingReverse = recursiveReverse(linkedList.next);

		// update the tail as beginning
		LinkedList current = remainingReverse;
		while (current.next != null) {
			current = current.next;

		}
		// assign the head as a tail
		current.next = linkedList;
		linkedList.next = null;

		return remainingReverse;
	}

	/**
	 * This method uses iterative approach to reverse a singly linked list.
	 */
	public static LinkedList iterativeReverse(LinkedList linkedList) {

		if (linkedList == null || linkedList.next == null) {
			return linkedList;
		}

		LinkedList prevNode, currNode, nextNode;
		prevNode = null;
		nextNode = null;
		currNode = linkedList;

		while (currNode != null) {
			nextNode = currNode.next;
			currNode.next = prevNode;
			prevNode = currNode;
			currNode = nextNode;
		}

		return prevNode;
	}

}
/**
 * Custom Linked List representation class
 */
class LinkedList {
	public LinkedList next;
	public int value;

	public LinkedList(int value) {
		this.value = value;
		this.next = null;
	}

	@Override
	public String toString() {

		String data = "";
		LinkedList current = this;
		do {
			data += current.value + ",";
			current = current.next;
		} while (current != null);

		return data;
	}
}


Output of running above program:

Original Linked List: 5,4,3,2,1,
Recursively Reversed List: 1,2,3,4,5,
Iteratively Recursed to Original: 5,4,3,2,1,

Insertion Sort Implementation In Java – Working Code Example

Insertion Sort Animation. Image Credit: Wikipedia / Creative Commons

Algorithm:

  • Take one element, compare with the one next to it and put in the order it belongs to, thus forming a partially sorted list.
  • Iterate through the list, one item at a time until no input elements remain.

Pseudo code is given below:

for i ← 1 to length(A)
j ← i
while j > 0 and A[j-1] > A[j]
swap A[j] and A[j-1]
j ← j - 1

Complexity:

  • Best Case: O(n) – For already sorted list
  • Average Case: O(n^2)
  • Worst Case: O(n^2)

Notes / Usage:

  • Insertion Sort is:
    • Stable
    • Takes O(1) extra space for swapping
    • In-Place Sorting – No extra memory is required
  • One real life usage of this kind of sorting is sorting a deck of cards.

Java Implementation Code:

package com.icodejava.blog.datastructure;

import java.util.Arrays;

/**
* @author Kushal Paudyal
* www.icodejava.com
* Created On -  Feb 26, 2014
* Last Modified On - Feb 26, 2014
*/
public class InsertionSort {

public static void main(String args[]) {
    int[] numberArray = { 5, 4, 7, 3, 3, 9, 0, 1, 2, 8, 6, -5 };

    sort(numberArray);

}

public static void sort(int[] numberArray) {

     System.out.println("Input Array: " + Arrays.toString(numberArray));

     for (int i = 1; i < numberArray.length; i++) { 			
         for (int j = i; j > 0; j--) {
             // Start comparing data with adjacent one and swap if smaller
             if (numberArray[j] < numberArray[j - 1]) {
             swap(numberArray, j, j - 1);
         }
     }
}

System.out.println("Sorted Array: " + Arrays.toString(numberArray));

}

/**
* Swaps data from an array.
*/
private static void swap(int[] array, int firstIndex, int secondIndex) {
   if (array == null || firstIndex < 0 || firstIndex > array.length 
     || secondIndex < 0 || secondIndex > array.length) {
    return;
   }
   int temp = array[firstIndex];
   array[firstIndex] = array[secondIndex];
   array[secondIndex] = temp;

}

}


Output of running above program:

Input Array: [5, 4, 7, 3, 3, 9, 0, 1, 2, 8, 6, -5]
Sorted Array: [-5, 0, 1, 2, 3, 3, 4, 5, 6, 7, 8, 9]

Selection Sort Implementation In Java – Working Code Example

Algorithm:

  • First find the smallest element in the array and exchange it with the element in the first position.
  • Then find the second smallest element and exchange it with the element in the second position.
  • Continue in this way until the entire array is sorted.

Complexity:

  • Best Case: n^2
  • Average Case: n^2
  • Worst Case: n^2

Notes:

  • Selection sort is an in-place comparison sort – thus taking O(1) memory space.
  • Selection sort is not stable**
  • Selection sort is a very simple algorithm
  • This sort is inefficient on large arrays.
  • Useful if less data movement is required. Selection sort has the lowest data movement. Useful when writing to Flash Memory.

When to use Selection Sort?

  • If the data is of small size
  • If I/O operations are more (since Selection Sort only writes n number of times). Specially when the sorting is done on a file rather than in memory
  • If simplicity is required rather than performance

**A sorting algorithm is said to be stable if two objects with equal keys appear in the same order in sorted output as they appear in the input unsorted array. Some sorting algorithms are stable by nature like Insertion sort, Merge Sort, Bubble Sort
Java Implementation:

package com.icodejava.blog.datastructure;

import java.util.Arrays;

/**
 * @author Kushal Paudyal
 * www.icodejava.com
 * Created On -  Feb 25, 2014
 * Last Modified On - Feb 25, 2014
 */
public class SelectionSort {

	public static void main(String args[]) {
		int[] numberArray = { 5, 4, 7, 3, 3, 9, 0, 1, 2, 8, 6, -5 };

		sort(numberArray);

	}

	public static void sort(int[] numberArray) {
		System.out.println("Input Array: " + Arrays.toString(numberArray));
		for (int i = 0; i < numberArray.length-1; i++) {
			int minIndex = i;
			for (int j = i+1; j < numberArray.length; j++) {
				if (numberArray[j] < numberArray[minIndex]) {
					minIndex = j;
				}

			}

			if(minIndex != i) {
				swap(numberArray, minIndex, i);
			}

		}

		System.out.println("Sorted Array: " + Arrays.toString(numberArray));
	}

	/**
	 * Swaps data from an array.
	 */
	private static void swap(int[] array, int firstIndex, int secondIndex) {
		if (array == null || firstIndex < 0 || firstIndex > array.length
				|| secondIndex < 0 || secondIndex > array.length) {
			return;
		}
		int temp = array[firstIndex];
		array[firstIndex] = array[secondIndex];
		array[secondIndex] = temp;

	}
}

Here is the output of running above Selection Sort program:

Input Array: [5, 4, 7, 3, 3, 9, 0, 1, 2, 8, 6, -5]
Sorted Array: [-5, 0, 1, 2, 3, 3, 4, 5, 6, 7, 8, 9]