微软算法100题58 从尾到头输出链表(java)
题目:输入一个链表的头结点,从尾到头反过来输出每个结点的值
以前做过相似的,可以用递归解决,也可以用非递归解决
1 package com.rui.microsoft; 2 3 import java.util.Stack; 4 5 public class Test_LinkedList { 6 7 public static void main(String[] args) { 8 Node<Integer> head = new Node<Integer>(0); 9 10 Node<Integer> node1 = new Node<Integer>(1); 11 Node<Integer> node2 = new Node<Integer>(2); 12 Node<Integer> node3 = new Node<Integer>(3); 13 14 head.next = node1; 15 node1.next = node2; 16 node2.next = node3; 17 18 Test_LinkedList app = new Test_LinkedList(); 19 20 //app.removeNodeWithO1(head, node3); 21 //app.print(head); 22 23 //Node<Integer> last = app.reverseRec(head); 24 //app.print(last); 25 26 Node<Integer> newHead = app.reverseNoRec2(head); 27 app.print(newHead); 28 } 29 30 //递归逆转链表 31 Node<Integer> reverseRec(Node<Integer> head){ 32 if(null == head) return head; 33 if(null == head.next) return head; 34 35 Node<Integer> last = reverseRec(head.next); 36 head.next = null; 37 last.next = head; 38 return head; 39 } 40 41 //非递归逆转链表 better 42 Node<Integer> reverseNoRec2(Node<Integer> head){ 43 if(null == head) return head; 44 if(null == head.next) return head; 45 46 Node<Integer> current = head.next; 47 Node<Integer> prev = head; 48 49 while(null != current){ 50 prev.next = current.next; 51 current.next = head; 52 head = current; 53 current = prev.next; 54 } 55 return head; 56 } 57 58 //非递归逆转链表 59 Node<Integer> reverseNoRec1(Node<Integer> head){ 60 if(null == head) return head; 61 if(null == head.next) return head; 62 63 Stack<Node<Integer>> stack = new Stack<Node<Integer>>(); 64 65 Node<Integer> node = head; 66 while(null!=node){ 67 stack.push(node); 68 node = node.next; 69 } 70 71 Node<Integer> newHead = stack.pop(); 72 Node tmp = newHead; 73 while(!stack.isEmpty()){ 74 tmp.next = stack.pop(); 75 tmp = tmp.next; 76 } 77 tmp.next = null; 78 return newHead; 79 } 80 81 //在O(1)时间内删除单向链表结点 82 void removeNodeWithO1(Node<Integer> head, Node<Integer> del){ 83 //If not tail 84 if(del.next != null){ 85 Node<Integer> temp = del.next; 86 del.value = temp.value; 87 del.next = temp.next; 88 temp = null; 89 } 90 else{ 91 Node node = head; 92 Node prev = head; 93 while(node != del){ 94 prev = node; 95 node = node.next; 96 } 97 98 prev.next = null; 99 del = null; 100 } 101 } 102 103 private void print(Node node){ 104 while(node != null){ 105 System.out.print(" " + node.value ); 106 node = node.next; 107 } 108 } 109 } 110 111 class Node<T>{ 112 T value; 113 Node<T> next; 114 115 public Node(T t){ 116 value = t; 117 } 118 }