我试图使链表反向并且也删除方法。

大多数情况下,程序可以正常运行,但是在remove()和reverseByLink()之间不兼容。

当我删除队列时,当我尝试使用reverseByLink之后,它根本不会反向。当我调试它时,它表明while loop(cur!= null)找到了空值。所以我不知道该怎么办。

void reverseBylink() {
    Node prev = null;
    Node current = this.first;
    Node next = null;
    Node temp = null;

        while (current != null) {
            next = current.next;
            current.next = prev;
            prev = current;
            current = next;
        }




     temp =first;
     first = last;
     last = temp;

 }


    //How to do this...;<..
int remove(Item item) {
    Node cur = this.first;
    Node prev = null;
    Node temp2 = null;


    while (cur != null) {

        if (cur.item.equals(item)) {
            if (prev != null) {

                prev.next = cur.next;
                cur = cur.next;



            } else {
                cur = cur.next;
                first = cur;



            }
        } else {
            prev = cur;
            cur = cur.next;


        }


    }

    temp2 = first;
    first  = last;
    last = temp2;

   return 0;
}









/**
 * Unit tests the <tt>LinkedQueue</tt> data type.
 */
public static void main(String[] args) {
    LinkedQueue<String> q = new LinkedQueue<String>();

   //Working properly for reverseByStack.
    q.enqueue("a");
    q.enqueue("b");
    q.enqueue("c");
    q.enqueue("a");
    q.enqueue("d");
    q.enqueue("b");
    q.enqueue("abba");
    q.enqueue("a");
    q.enqueue("z");
    q.enqueue("a");
    q.reverseBystack();

    System.out.println(q);
    q.remove("a");
    q.remove("f");
    q.remove("c");
    q.reverseBylink();

    System.out.println(q);
}
  }


这些是我做的。

你能帮我我需要改变的地方吗?

最佳答案

尝试一下是否适合您:

void reverseBylink() {
    Node tail = null;
    while( this.first != null) {
          Node current = this.first;
          this.first = this.first.next;
          current.next = tail;
          tail = current;
     }
     this.first = tail;
 }

07-27 16:46