Get into the habit of writing together! This is the 17th day of my participation in the "Nuggets Daily New Plan · April Update Challenge", click to view the details of the event .
topic
Reverse Linked List Give you the head node of the singly linked list, please reverse the linked list and return the reversed linked list. Example 1:
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
复制代码
Example 2:
输入:head = [1,2]
输出:[2,1]
复制代码
Example 3:
输入:head = []
输出:[]
复制代码
hint:
- The number of nodes in the linked list ranges from
[0, 5000]
-5000 <= Node.val <= 5000
Advanced: The linked list can be reversed in an iterative or recursive way. Can you solve this problem in two ways?
answer
problem-solving analysis
Problem solving ideas
- Iterative processing
- Suppose the linked list data is
1->2->3->end
, we need to modify it toend->3->2-1
. - When traversing, modify the current
next
pointer to point to the previous node. Since the node does not refer to the previous node, the previous node must be stored beforehand. Before modifying the reference, it is also necessary to store the latter node, and return the new head node after the final execution is completed. - It takes one cycle to complete the reversal.
the complexity
Time complexity O(N)
Space complexity O(1)
problem solving code
The solution code is as follows (detailed comments in the code):
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null ;
ListNode curr = head;
// 直接迭代反转
while(curr != null) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
}
复制代码
Feedback results after submission (because this topic has not been optimized, the performance is average):
- Another solution (recursion), the core code is
ead.next.next = head
.
class Solution {
public ListNode reverseList(ListNode head) {
// 如果头为空,或者只有一个节点
if (head == null || head.next == null) {
// 递归出口
return head;
}
// 递归调用
ListNode newHead = reverseList(head.next);
// 这里很难理解本质就是将
// 1->2->end 转换为 end->2->1
head.next.next = head;
// 防止出现环
head.next = null;
return newHead;
}
}
复制代码