-
Notifications
You must be signed in to change notification settings - Fork 7.1k
/
ReverseNode.java
106 lines (78 loc) · 1.91 KB
/
ReverseNode.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package com.crossoverjie.algorithm;
import java.util.Stack;
/**
* Function: 三种方式反向打印单向链表
*
* @author crossoverJie
* Date: 10/02/2018 16:14
* @since JDK 1.8
*/
public class ReverseNode {
/**
* 利用栈的先进后出特性
* @param node
*/
public void reverseNode1(Node node){
System.out.println("====翻转之前====");
Stack<Node> stack = new Stack<>() ;
while (node != null){
System.out.print(node.value + "===>");
stack.push(node) ;
node = node.next ;
}
System.out.println("");
System.out.println("====翻转之后====");
while (!stack.isEmpty()){
System.out.print(stack.pop().value + "===>");
}
}
/**
* 利用头插法插入链表
* @param head
*/
public void reverseNode(Node head) {
if (head == null) {
return ;
}
//最终翻转之后的 Node
Node node ;
Node pre = head;
Node cur = head.next;
Node next ;
while(cur != null){
next = cur.next;
//链表的头插法
cur.next = pre;
pre = cur;
cur = next;
}
head.next = null;
node = pre;
//遍历新链表
while (node != null){
System.out.println(node.value);
node = node.next ;
}
}
/**
* 递归
* @param node
*/
public void recNode(Node node){
if (node == null){
return ;
}
if (node.next != null){
recNode(node.next) ;
}
System.out.print(node.value+"===>");
}
public static class Node<T>{
public T value;
public Node<T> next ;
public Node(T value, Node<T> next ) {
this.next = next;
this.value = value;
}
}
}