pigpug pee
pigpug pee

Reputation: 35

Linked java list

Im trying to make Linked List Reverse and also remove method.

Mostly the program working properly, but It is not compatible between remove() and reverseByLink().

when I remove queue and after when I try to use reverseByLink it doesn't reverse at all. When I debug it, it is showing that while loop(cur != null) has found null value. So I don't know what to do.

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);
}
  }

these are what i made.

could you please help me what I need to change?

Upvotes: 0

Views: 67

Answers (2)

Alexander Khlystov
Alexander Khlystov

Reputation: 91

Try looking into existing collection libraries from Guava etc...

Upvotes: 1

kai
kai

Reputation: 905

Try if that works for you:

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;
 }

Upvotes: 1

Related Questions