0

Well it seems like I'm running into a infinite loop trying to reverse this list. so say I have some random numbers like 4,5,6,7 and I was trying reverse it to 7,6,5,4. I started with the node at the the head and added it to end the last node until i get the final list(IE 7,4 ->7,5,4,) but every I've attempted was giving me infinite loops.

    public void Reversing() {
    Node<E> currently = this.head;//set it to head to loo[
    Node<E> last = this.head;
    Node<E> temp = this.head; //not used anymore

    last=lastNode();//gets the last item in the list

    while (currently != null) {//loop until not null
        last.next=currently;
        currently=currently.next;

        if(last.info==currently.info){//break out of loop
            break;
        }  
    }
}
Sam Kohnson
  • 115
  • 1
  • 3
  • 11
  • 1
    if you want to reverse the linked list, would a doubly linked list work for you? Then you can have a method to iterate backwards? – benscabbia Apr 10 '15 at 06:03
  • These are popular interview questions where you are expected not to do things that are obvious. – Jagannath Apr 10 '15 at 06:05
  • You might want to consider creating a new `Node` for your new list. Grab the `last` of the old list, delete it, and then make the `next` of the new node equal to it. – Eric Groves Apr 10 '15 at 06:05
  • possible duplicate of [Reverse Singly Linked List Java](http://stackoverflow.com/questions/22605050/reverse-singly-linked-list-java) – dting Apr 10 '15 at 06:15
  • can u paste the code for lastNode() ? – Balaji Katika Apr 10 '15 at 06:19

1 Answers1

1

You are reversing a singly linked list. See this SO question that shows how to do it Reverse Singly Linked List Java

I'll copy in the answer:

Node<E> reversedPart = null;
Node<E> current = head;
while (current != null) {
    Node<E> next = current.next;
    current.next = reversedPart;
    reversedPart = current;
    current = next;
}
head = reversedPart;
Community
  • 1
  • 1
Upio
  • 1,364
  • 1
  • 12
  • 27