Difficulty:easy
More:【目录】LeetCode Java实现
Description
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?
Intuition
refer to 反转链表
pay attention : head.next=null
Solution
/*recursively*/
public ListNode reverseList(ListNode head) {
ListNode newHead=reverse(null,head);
return newHead;
}
private ListNode reverse(ListNode pre,ListNode cur){
if(cur==null)
return pre;
ListNode next=cur.next;
cur.next=pre;
return reverse(cur,next);
}
/*iteratively*/
public ListNode reverseList2(ListNode head) {
ListNode pre = null;
ListNode cur = head;
while(cur!=null){
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
Complexity
recursively:
Time complexity : O(n)
Space complexity : O(n)
iteratively:
Time complexity : O(n)
Space complexity : O(1)
What I've learned
1. When it comes to the Linked List, we should make the best of pointer.
More:【目录】LeetCode Java实现