1

I am trying to implement the linkedList class, adding a method reverse(int n) to reverse the linked list. For example, I have a linked list { A -> B -> C -> D -> E). When I call reverse(4), the linked list will become D-->C-->B-->A-->E.

I am trying to avoid using iterator, constructing new node and copying the data value. Does anyone have idea how to do it? I know there was a post about reversing linked list but that one is reversing the entire linked list.

Thank you so much for the help!

1
  • Just use the same principle. Commented Oct 31, 2015 at 20:31

1 Answer 1

1

Since you don't provide your implementation of the LinkedList, i can only provide the general idea:
The complete list can be reversed by simply swaping the pointers to the previous node and the next node and updating the fields for the last and first node.

void reverse()
    node tmp = first
    first = last
    last = tmp

    while(tmp.next != null)
        node swap = tmp.next
        tmp.next = tmp.previous
        tmp.previous = swap

        tmp = swap

I'll leave it to you to add the bounds

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.