leetcode-206-Reverse Linked List

Reverse a singly linked list.

Example:

1
2
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

Follow up:

A linked list can be reversed either iteratively or recursively. Could you implement both?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null)
return head;
ListNode prev = null;
ListNode curr = head;
prev = new ListNode(curr.val);
curr = curr.next;
while(curr != null)
{
ListNode temp = new ListNode(curr.val);
temp.next = prev;
prev = temp;
curr = curr.next;
}
return prev;
}
}
Donate? comment?