Approach
# 走訪linked-list,注意交換數值的順序
Traverse the linked-list, paying attention to the order of value swaps.
Time Complexity
# n = length of list
O(n)
Space Complexity
# n = length of list
O(n)
Code
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *prev = NULL, *cur = head, *next = NULL;
while (cur != NULL) {
next = cur -> next;
cur -> next = prev;
prev = cur;
cur = next;
}
return prev;
}
};