Reverse a singly linked list.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
/*First initialize a pointer 'newHead' pointing to null. In each iteration, we do four steps.
1. New a 'tmp' pointer pointing to 'head.next';
2. Let 'head.next' connect to 'newHead';
3. Let 'newHead' point to 'head';
4. Let 'head' point to 'tmp'.
time: O(n), space:O(1)
*/
public class Solution {
public ListNode reverseList(ListNode head) {
if (head == null) {
return head;
}
ListNode newHead = null;
while (head != null) {
ListNode tmp = head.next;
head.next = newHead;
newHead = head;
head = tmp;
}
return newHead;
}
}
No comments:
Post a Comment