java - IntList 排序方法
问题描述
我的问题是如何在我的 IntList 类中实现排序方法。我正在尝试使用下面显示的排序方法(这不起作用,只是一个起点),我知道的一些事情是这种方法在 IntList 类中,所以我不应该需要除 IntList 之外的其他文件和康斯细胞。IntList 知道的是它的构造函数和两个访问器:长度和打印。IntList 由知道构造函数、getHead、getTail 和 setTail 的 ConsCell(链表)组成。如果有人能指出我正确的方向,将不胜感激。
// IntList Class
public class IntList {
private ConsCell start;
public IntList(ConsCell s) {
start = s;
}
public IntList cons (int h) {
return new IntList(new ConsCell(h,start));
}
public int length() {
int len = 0;
ConsCell cell = start;
while (cell != null) {
len++;
cell = cell.getTail();
}
return len;
}
public void print() {
System.out.print("[");
ConsCell a = start;
while (a != null){
System.out.print(a.getHead());
a = a.getTail();
if (a != null) System.out.print(",");
}
System.out.println("]");
}
public static int[] sort(int [] arr){
int length = IntList.len();
for (int j = 0; j < length - 1; j++){
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
return arr;
}
}
// ConsCell Class
public class ConsCell {
private int head;
private ConsCell tail;
public ConsCell(int h, ConsCell t) {
head = h;
tail = t;
}
public int getHead() {
return head;
}
public ConsCell getTail() {
return tail;
}
public void setTail(ConsCell t) {
tail = t;
}
}
//Main Class
public class Main {
public static void main(String args[]){
IntList a = new IntList(null);
IntList b = a.cons(2);
IntList c = b.cons(1);
IntList d = c.cons(3);
int x = a.length() + b.length() + c.length() + d.length();
a.print();
b.print();
c.print();
d.print();
// x.sort() // sorting, will use later
System.out.println(x);
}
}
解决方案
推荐阅读
- c - 如何修改 glibc 中的 malloc 行为并测试它是否按预期工作?
- python - 在 Kivy 上按下按钮时如何显示文本
- javascript - 如何将数据从 React 发送到 Flask,然后返回以响应并在 DOM 上显示输出
- reactjs - React Navigation - 导航并设置后退按钮的历史记录
- xcode - IOS应用权限
- visual-studio-code - 如何做一个弹出窗口
- oauth - 在对任何网站进行身份验证后,我可以获得我的 JWT 吗?
- php - 如何使用 php 获取 iframe 的视频元素的 url
- python - 在Python中获取彩色形状周围的边界坐标
- unity3d - 我找不到输入调试器面板