So I need to reverse a Linked List in O(N) time/space.
This implementation is what I came up with using only the LinkedList class in the Java standard library (which doesn’t give me access to the nodes themselves).
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
No, it’s not.
input.get(idx);is itselfO(idx)in time, which makes your implementation quadratic in time.You will probably want to use an iterator (or better yet
listIterator).EDIT: Also, you could easily eliminate holdPopped with a little rearrangement.
holdPopped.addwill be trivially O(1) in both time and space since you’re pre-allocating space (which is O(n) in space) by passing the size.IIRC,
holdLL.addis amortized O(1) in time and space as well. Sometimes it will be more, sometimes less, but the total space is n, so it should average to to O(n). You can simplify the analysis by usingholdLL.ensureCapacity.