交换两个元素

时间:2016-01-14 20:46:15

标签: java list

我写了一个简单易用的代码来交换列表中的两个元素,如下所示:

public void swap(Item a, Item aprev, Item b, Item bprev){
    aprev.next = b;
    bprev.next = a;
}

现在。如果我想实际交换两个元素,没有什么真正改变。所以,如果我这样做:

SelectionSortableList list = new SelectionSortableList();
    Item item =  list.new Item("4");
    Item item1 =  list.new Item("5");
    Item item2 =  list.new Item("6");
    Item item3 =  list.new Item("7");
    list.addFront(item.value);
    list.addFront(item1.value);
    list.addFront(item2.value);
    list.addFront(item3.value);

    System.out.println(list.toString());
    list.swap(item1, item, item3, item2);
    System.out.println(list.toString());





/*    */ public abstract class SinglyLinkedList
/*    */ {
/*    */   protected SinglyLinkedList.Item head;
/*    */   
/*    */   public void addFront(String s) {
/*  6 */     if (head == null) {
/*  7 */       head = new SinglyLinkedList.Item(s);
/*    */     }
/*    */     else {
/* 10 */       SinglyLinkedList.Item insert = new SinglyLinkedList.Item(s);
/* 11 */       next = head;
/* 12 */       head = insert;
/*    */     }
/*    */   }
/*    */   
/*    */   public void add(String[] array) { String[] arrayOfString;
/* 17 */     int j = (arrayOfString = array).length; 
            for (int i = 0; i < j; i++) { String s = arrayOfString[i];
/* 18 */       addFront(s);
/*    */     }
/*    */   }
/*    */   
/*    */   public String toString()
/*    */   {
/* 24 */     if (head == null) {
/* 25 */       return "empty list";
/*    */     }
/* 27 */     String s = "";
/*    */     
/* 29 */     for (SinglyLinkedList.Item helper = head; next != null;
 helper = next) {
/* 30 */       s = String.valueOf(s) + value + ", ";
/*    */     }
/* 32 */     s = String.valueOf(s) + value;
/* 33 */     return s;
/*    */   }
/*    */   
/*    */   public abstract void sort();
/*    */   
/*    */   protected class Item
/*    */   {
/*    */     public Item next;
/*    */     public String value;
/*    */     
/*    */     public Item(String value) {
/* 44 */       this.value = value;
/*    */     }
/*    */   }
/*    */ }

很抱歉这个烂摊子,但它是一个反编译的jar。这是我尚未完成的课程:

public class SelectionSortableList extends SinglyLinkedList{

public Item head;

public SelectionSortableList(){
    this.head = new Item(null);
}


public void swap(Item a, Item aprev, Item b, Item bprev){
    aprev.next = b;
    bprev.next = a;
}

没有任何改变,他像以前一样打印我完全相同的列表。我真的不知道为什么这不起作用。如果有人可以给我一个提示,或者如果我应该多写一点,那就太棒了。先谢谢你:))

1 个答案:

答案 0 :(得分:0)

首先,值得一提的是,为什么你必须选择这样做,而不是使用Java Collections Framework中的类。

但即使你出于教育目的这样做,例如了解列表中运行的列表数据结构和算法,我建议首先使用标准Java API对其进行编程,例如在this example中。

然后,要了解内部发生了什么,请按照使用过的类的来源进行操作。您可以在OpenJDK projectnicely browsable here找到它。

了解了这一点后,您可以返回并实现自己的版本,并且(例如,如果您必须)使用给定的数据结构。

关于你的具体问题 - 我还没有尝试过(你应该按照之前的建议调试),但我假设在扩展类并使用相同的成员变量名时,你会影响基类一个,因此不要对它进行操作。所以你应该扩展功能,但要处理相同的数据结构。

相关问题