首页 > 解决方案 > 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);
  
    }
  }

标签: java

解决方案


推荐阅读