Simple Java 0ms solution, reverse in place with two pointers


  • 0
    D

    "tail" points to the next node to be put in front, while "pHead" points to the head of the remaining list to be reversed.

    public class Solution {
        public ListNode reverseList(ListNode head) {
            ListNode stub = new ListNode(0);
            ListNode tail = head, pHead;
            while(tail!=null){
                pHead = tail.next;
                tail.next = stub.next;
                stub.next = tail;
                tail = pHead;
            }
            return stub.next;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.