연결 리스트를 뒤집어라
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
Input: head = [1,2]
Output: [2,1]
Input: head = []
Output: []
/**
* 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 {
private:
ListNode* rhead;
ListNode* rtail;
stack<int> st;
public:
void addNode(int n)
{
ListNode* temp = new ListNode;
temp->val = n;
temp->next = NULL;
if(rhead == NULL)
{
rhead = temp;
rtail = temp;
}
else
{
rtail->next = temp;
rtail = temp;
}
}
void pushStack(ListNode* head)
{
if (head == NULL)
{
cout << "\n";
}
else
{
st.push(head->val);
if(head->next != NULL) pushStack(head->next);
}
}
ListNode* reverseList(ListNode* head)
{
pushStack(head);
while (!st.empty())
{
addNode(st.top());
st.pop();
}
return rhead;
}
};
Runtime 8 ms / Memory 88 MB
https://leetcode.com/problems/reverse-linked-list/submissions/893526853/