206. Reverse Linked List

Andreea
2 min readMay 1, 2021

Given the head of a singly linked list, reverse the list, and return the reversed list.

Example 1:

Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]

Example 2:

Input: head = [1,2]
Output: [2,1]

Example 3:

Input: head = []

CODE use C++:

/**
* 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) {
int len = 0, now = 0, end = 0;
ListNode *tmp = head;
if(head == NULL){
return head;
}
while(tmp->next != NULL){
tmp = tmp->next;
end++;
len++;
}
int tmp_int = head->val;
head->val = tmp->val;
tmp->val = tmp_int;
now++;
end--;
ListNode *tmp_head = head;
while(end>now){
int tmp_now = end;
tmp = head;
while(tmp_now!=0){
tmp = tmp->next;
tmp_now--;
}
tmp_head = tmp_head->next;
int tmp_int = tmp_head->val;
tmp_head->val = tmp->val;
tmp->val = tmp_int;
end--;
now++;
}
return head;


}


};

Runtime: 28 ms, faster than 57.91% of C++ online submissions for Reverse Linked List.

Memory Usage: 8.3 MB, less than 75.89% of C++ online submissions for Reverse Linked List.

--

--