Reverse linked list
Description: Reverse a singly linked list.
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
This article uses an iterative method to reverse the linked list. The
basic idea: When traversing, point the next node of the current node to the previous node
. Problems that occur:
- Due to the one-way link list, the address of the previous node is unknown
- If you change the next value of the current node, the address of the subsequent node will be lost
Solution:
- Use prev and cur pointers to point to the predecessor and current node respectively
- Store the address of the subsequent node in nextTemp
The process is shown in the figure below (only three nodes are listed) and the
code is as follows:
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode cur = head;
while(cur != null){
ListNode nextTemp = cur.next;
cur.next = prev;
prev = cur;
cur = nextTemp;
}
return prev;
}
}
Complexity analysis:
Time complexity: O(n)
Space complexity: O(1)