/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode prev = null;
while (head != null)
{
/*
head: head -> (val = 1, next=head2) // head2 is origin head.next;
1
temp: HEAD.next -> head2(val = 2, next=head3)
HEAD.next(head2): prev(null)
* head1(HEAD) => (val = 1, next=null)
prev: head -> head1(val = 1, next = null)
head: temp: HEAD.next -> head2(val = 2, next = head3(original) )
2
temp: HEAD.next.next -> head3(val = 3, next=head4) // head3 is origin head.next.next;
head2.next(head3): prev: head -> head1(val = 1, next = null)
* head2(HEAD.next) => head1(val=1, next=null);
prev: head.next -> head2(val=2, next=head1)
head: head3(val=3, next=head4)
3
temp: HEAD.next.next.next -> head4(val = 4, next=head5)
head3.next(head4) -> prev: head2(val=2, next=head1)
* head3(HEAD.next.next) => head3(val=3, next=head2);
prev: head.next.next -> head3(val=3, next=head2);
head: head4(val=4, next=head5);
4
temp: HEAD.next.next.next.next -> head5(val = 5, next=null)
head4.next(head5) -> prev: head3(val=3, next=head2)
* head4(HEAD.next.next.next) => head4(val=4, next=head3);
prev: head.next.next.next -> head4(val=4, next=head3);
head: head5(val=5, next=null);
5
temp: HEAD.next.next.next.next.next -> head6(null)
head5.next(head6) -> prev: head4(val=4, next=head3)
* head5(HEAD.next.next.next.next) => head5(val=5, next=head4);
prev: head.next.next.next.next -> head5(val=5, next=head4);
head: head6(null);
head: null => false: escape;
*/
ListNode temp = head.next;
head.next = prev;
prev = head;
head = temp;
}
return prev;
}
}
Time: O(N)
Space: O(1), constant