-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathReversor.java
More file actions
64 lines (50 loc) · 1.17 KB
/
Copy pathReversor.java
File metadata and controls
64 lines (50 loc) · 1.17 KB
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
/**
* author : wangjinlei
* email : sea11107@mail.ustc.edu.cn
*/
class Node {
public int data;
public Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
public Node head;
public LinkedList() {
head = null;
}
// insert a node at the head of the list
public LinkedList append(Node node) {
node.next = head;
this.head = node;
return this;
}
// an elegant way to print the list
public String toString() {
StringBuilder sbuf = new StringBuilder();
for (Node begin= this.head; begin != null; begin = begin.next) {
sbuf.append(begin.data).append(",");
}
return sbuf.toString();
}
public void reverse() {
if (this.head == null)
return;
this.head = reverseHelper(null, head, head.next);
}
private Node reverseHelper(Node t, Node p, Node q) {
p.next = t;
return (q == null) ? p : reverseHelper(p, q, q.next);
}
}
public class Reversor {
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.append(new Node(1)).append(new Node(2));//.append(new Node(3)).append(new Node(4));
System.out.println(list);
list.reverse();
System.out.println(list);
}
}