Thursday, 21 January 2016

Reverse linked list in place

Found this harder than expected as I knocked out the list in 5 minutes, reverse in place I had to look up then had the ah yeah I see moment, I did get some practice around visualising a problem.

public class MyLinkedList {
    public Node head = null;
    public Node tail = null;
   
    public void append(int valueToAdd) {
        if    (head == null && tail == null) {
            head = tail = new Node(valueToAdd);
        } else {
            tail.nextNode = new Node(valueToAdd);
            tail = tail.nextNode;
        }
    }
   
    public void printList() {
        Node aNode = head;
        while (aNode != null) {
            System.out.println(aNode.value);
            aNode = aNode.nextNode;
        }
    }
   
    public void reverse() {
        Node a = null, b = null, c = head;
        tail = head;
        while (c != null) {
            a = c.nextNode;
            c.nextNode = b;
            b = c;
            c = a;
        }
        head = b;
    }
   
    class Node {
        public int value;
        public Node nextNode = null;
      
        public Node(int valueToAdd) {
            this.value = valueToAdd;
        }
    }
}

No comments:

Post a Comment