简单常用算法


单链表反转

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
class Node {
Node(int v, Node n) {
this.val = v;
this.next = n;
}
int val;
Node next;
}
public class App {
public static Node reverse(Node node) {
Node pre = node;
Node cur = node.next;
Node tmp;
while (cur != null) {
tmp = cur.next;
cur.next = pre;
pre = cur;
cur = tmp;
}
node.next = null;
return pre;
}
public static void main(String []args) {
Node node = new Node(1, new Node(2, new Node(3, new Node(4, null))));

Node res = reverse(node);
while (res != null) {
System.out.print(res.val + "->");
res = res.next;
}
}
}

结果:

D:\B\A>javac App.java

D:\B\A>java App
4->3->2->1->
D:\B\A>

快速排序