题目:
Reverse a singly linked list.
Example:
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?
public class ReverseLinkedList {
public static ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode cur = head;
while(cur != null) {
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
public static void main(String[] args) {
int[] nums = {1, 2, 3, 4, 5};
ListNode head = createLinkedList(nums, nums.length);
printLinkedList(head);
ListNode reverseList = reverseList(head);
printLinkedList(reverseList);
}
public static ListNode createLinkedList(int arr[], int n){
if (n == 0)
return null;
ListNode head = new ListNode(arr[0]);
ListNode cur = head;
for (int i = 1; i < n; i++) {
cur.next = new ListNode(arr[i]);
cur = cur.next;
}
return head;
}
public static void printLinkedList(ListNode head){
ListNode cur = head;
while (cur != null){
System.out.print(cur.val + " -> ");
cur = cur.next;
}
System.out.println("NULL");
}
}
class ListNode {
public int val;
public ListNode next;
public ListNode(int x) {
val = x;
}
}