Pergunta de entrevista da empresa LinkedIn

linked list reversal

Resposta da entrevista

Sigiloso

14 de mar. de 2011

package singh.vishwesh.thakur.dynamicprog; public class SinglyLinkedList { private Node head; public SinglyLinkedList() { super(); } public void add(T data) { head = new Node(data, head); } public void reverse() { if(head == null || head.getNext() == null) { return; } Node r = head; Node u = head.next; Node uNext = u.next; r.next = null; while(u != null) { u.next = r; r = u; u = uNext; uNext = uNext != null ? uNext.next : null; } head = r; } public String toString() { StringBuffer buf = new StringBuffer(); Node curr = head; while(curr != null) { buf.append(curr.data + ", "); curr = curr.getNext(); } return buf.toString(); } public static void main(String[] args) { SinglyLinkedList l = new SinglyLinkedList(); l.add(1); l.add(2); l.add(3); l.add(4); l.add(5); l.add(6); l.add(7); System.out.println(l); l.reverse(); System.out.println(l); } static class Node { private T data; private Node next; public T getData() { return data; } public void setData(T data) { this.data = data; } public Node getNext() { return next; } public void setNext(Node next) { this.next = next; } public Node(T data, Node next) { super(); this.data = data; this.next = next; } } }