Reverse LinkedList

来源:互联网 发布:sql高阶 编辑:程序博客网 时间:2024/06/04 08:23
//Time Complexity: O(N), Space Complexity: O(N).public static Node recursive(Node head) {if(head == null || head.next == null) {return head;}Node recursiveNode = recursive(head.next);head.next.next = head;head.next = null;return recursiveNode;}//Time Complexity: O(N), Space Complexity: O(1).public static Node iterative(Node head) {if(head == null) {return null;}Node previous = head;Node current = head;while(head.next != null) {current = head.next;head.next = current.next;current.next = previous;previous = current;}return previous;}