Java栈与队列的实现

lkpalu Lv3

前言

栈与队列的实现采用动态分配内存,保证了使用的灵活性

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
package Stack;

import java.util.Arrays;

public class Stack {
int length = 0;
int[] arr;
public Stack() {
this.length = 0;
arr = new int[this.length];
}
public Stack(int length) {
this.length = length;
arr = new int[this.length];
}
public void Push(int val) {
this.length++;
int[] tmp = new int[this.length];
for (int i = 0;i <this.length - 1;i++) {
tmp[i] = arr[i];
}
tmp[this.length - 1] = val;
// System.out.println(Arrays.toString(tmp));
arr = tmp;
}
public int GetLength() {
return this.length;
}
public int Pop() {
int val = this.arr[this.length - 1];
this.length--;
int[] tmp = new int[this.length];
for (int i = 0;i<this.length;i++) {
tmp[i] = arr[i];
}
arr = tmp;
return val;
}
@Override
public String toString() {
return "Queue{" +
"length=" + length +
", arr=" + Arrays.toString(arr) +
'}';
}
}

队列

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
package Queue;

import java.util.Arrays;

public class Queue {
int[] arr;
int length;

public Queue() {
this.length = 0;
this.arr = new int[this.length];
}

public Queue(int length) {
this.length = length;
this.arr = new int[this.length];
}

public void Push(int val) {
this.length++;
int[] tmp = new int[this.length];
for (int i = 0; i < this.length - 1; i++) {
tmp[i] = arr[i];
}
tmp[this.length - 1] = val;
arr = tmp;
}

public void LPush(int val) {
this.length++;
int[] tmp = new int[this.length];
for (int i = 0; i < this.length - 1; i++) {
tmp[i+1] = arr[i];
}
tmp[0] = val;
arr = tmp;
}

public int Pop() {
int val = this.arr[0];
this.length--;
int[] tmp = new int[this.length];
for (int i = 0; i < this.length; i++) {
tmp[i] = arr[i + 1];
}
arr = tmp;
return val;
}
public int RPop() {
int val = this.arr[this.length - 1];
this.length--;
int[] tmp = new int[this.length];
for (int i = 0; i < this.length; i++) {
tmp[i] = arr[i];
}
arr = tmp;
return val;
}

public int GetLength() {
return this.length;
}

@Override
public String toString() {
return "Queue{" +
"arr=" + Arrays.toString(arr) +
", length=" + length +
'}';
}
}
  • 标题: Java栈与队列的实现
  • 作者: lkpalu
  • 创建于 : 2024-11-12 08:55:51
  • 更新于 : 2024-11-12 08:59:00
  • 链接: https://redefine.ohevan.com/2024/11/12/Java栈与队列的实现/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
评论
目录
Java栈与队列的实现