Meta Interview Question

reverse of a linked list

Interview Answers

Anonymous

Apr 4, 2015

using recursion class Node { int data; Node next; Node(int data) { this.data=data; next=null; } } class ReverseLLRecursion { static Node reverse(Node head) { if(head.next==null) return head; reverse(head.next).next=head; head.next=null; return head; } public static void main(String[] st) { Node n1=new Node(1); Node n2=new Node(2); Node n3=new Node(3); Node n4=new Node(4); n1.next=n2; n2.next=n3; n3.next=n4; reverse(n1); Node tra=n4; while(tra!=null) { System.out.println(tra.data+", "); tra=tra.next; } } }

Anonymous

Feb 9, 2015

Given a LinkedList of Node (val, next), below is an in-place reverse function: // Class: Node var Node = function(val) { this.val = val; this.next = null; }; // Assuming there is a linked-list with 2 nodes var reverse = function(linkedList) { var previous = linkedList.head, current = previous.next, next ; previous.next = null; while(current != null) { next = current.next; current.next = previous; previous = current; current = next; } linkedList.head = previous; };