冒泡排序1
2
3
4
5
6
7
8
9
10
11int num[]={1,3,5,10,2,90,30,20,10,9};
for(int i=0;i<num.length;i++) {
for(int j=i+1;j<num.length;j++) {
if (num[i] < num[j]) {//从大到小排序
num[i] = num[i] + num[j];
num[j] = num[i] - num[j];
num[i] = num[i] - num[j];
}
}
}
求素数(高效) C语言版及解析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/**
* 假如所求素数很大时,此方法效率很高
*/
public static List<Integer> getPrimeNumber(int from, int to) {
if (from <= 0 || from >= to) {
return null;
}
List<Integer> prime = new ArrayList<Integer>();
// 首先定义一个比所求素数大1的数组
boolean result[] = new boolean[to + 1];
// 排除偶数
for (int i = 2; i <= to; i++) {
result[i] = i % 2 != 0;
}
// 排除所有从3到开平方数的倍数
for (int i = 3; i <= Math.sqrt(to); i++) {
if (result[i]) {
for (int j = i + i; j < to; j += i) {
result[j] = false;
}
}
}
for (int i = from; i <= to; i++) {
if (result[i]){
prime.add(i);
}
}
return prime;
}
请使用java或者C++实现反转单链表 原文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/**
* 定义一个单链表
*/
class Node {
//变量
private int record;
//指向下一个对象
private Node nextNode;
public Node(int record) {
super();
this.record = record;
}
public int getRecord() {
return record;
}
public void setRecord(int record) {
this.record = record;
}
public Node getNextNode() {
return nextNode;
}
public void setNextNode(Node nextNode) {
this.nextNode = nextNode;
}
}
/**
* @author luochengcheng
* 两种方式实现单链表的反转(递归、普通)
* 新手强烈建议旁边拿着纸和笔跟着代码画图(便于理解)
*/
public class ReverseSingleList {
/**
* 递归,在反转当前节点之前先反转后续节点
*/
public static Node reverse(Node head) {
if (null == head || null == head.getNextNode()) {
return head;
}
Node reversedHead = reverse(head.getNextNode());
head.getNextNode().setNextNode(head);
head.setNextNode(null);
return reversedHead;
}
/**
* 遍历,将当前节点的下一个节点缓存后更改当前节点指针
*
*/
public static Node reverse2(Node head) {
if (null == head) {
return head;
}
Node pre = head;
Node cur = head.getNextNode();
Node next;
while (null != cur) {
next = cur.getNextNode();
cur.setNextNode(pre);
pre = cur;
cur = next;
}
//将原链表的头节点的下一个节点置为null,再将反转后的头节点赋给head
head.setNextNode(null);
head = pre;
return head;
}
public static void main(String[] args) {
Node head = new Node(0);
Node tmp = null;
Node cur = null;
// 构造一个长度为10的链表,保存头节点对象head
for (int i = 1; i < 10; i++) {
tmp = new Node(i);
if (1 == i) {
head.setNextNode(tmp);
} else {
cur.setNextNode(tmp);
}
cur = tmp;
}
//打印反转前的链表
Node h = head;
while (null != h) {
System.out.print(h.getRecord() + " ");
h = h.getNextNode();
}
//调用反转方法
head = reverse2(head);
System.out.println("\n**************************");
//打印反转后的结果
while (null != head) {
System.out.print(head.getRecord() + " ");
head = head.getNextNode();
}
}
}
死锁(同步嵌套同步且锁不同)
1 | { |