Easy Reverse Linked ListMy Submissions
37%
Accepted
Reverse a linked list.
Example
Tags Expand
For linked list 1->2->3, the reversed linked list is 3->2->1
SOLUTION 1 directly distort the direction of the pointer. BETTER
Oriented the pointer direction to let the current node point to its original previous node. ListNode prev is initialized to Null. At last, we return prev of head is Null.
public class Solution {
/**
* @param head: The head of linked list.
* @return: The new head of reversed linked list.
*/
public ListNode reverse(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode prev = null;
while (head != null) {
ListNode temp = head.next;
head.next = prev;
prev = head;
head = temp;
}
return prev;
}
SOLUTION 2 Let tail.next to be the new Head.
Add the last to the front.
public class Solution {
/**
* @param head: The head of linked list.
* @return: The new head of reversed linked list.
*/
public ListNode reverse(ListNode head) {
// write your code here
if (head == null || head.next == null) {
return head;
}
ListNode tail = head;
while (tail.next != null) {
ListNode temp = tail.next.next;
tail.next.next = head;
head = tail.next;
tail.next = temp;
}
return head;
}
}