23. Reverse Linked List
02 Jul 2020 | Daily Algorithms
- my solution
/**
* 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* p = head;
vector<int> stack;
int size_=0;
while(p)
{
stack.push_back(p->val);
size_++;
p=p->next;
}
int i = 0;
ListNode* q = head;
while(i<size_)
{
cout<<stack.back()<<" ";
q->val = stack.back();
stack.pop_back();
q = q->next;
i++;
}
return head;
}
};
- my solution
/**
* 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* p = head;
vector<int> stack;
int size_=0;
while(p)
{
stack.push_back(p->val);
size_++;
p=p->next;
}
int i = 0;
ListNode* q = head;
while(i<size_)
{
cout<<stack.back()<<" ";
q->val = stack.back();
stack.pop_back();
q = q->next;
i++;
}
return head;
}
};
Comments