206. Reverse Linked List

Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
Input: head = [1,2]
Output: [2,1]
Input: head = []
/**
* 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;


}


};

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store