反转链表
题目链接
解题思路
- 反转链表,只需要将链表中的元素放入栈中,然后依次出栈,即可实现链表的反转
/*** 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) {stack<int> s;ListNode *res = new ListNode();ListNode *last = res;while(head != nullptr){int temp = head->val;s.push(temp);//元素入栈head = head->next;}while(!s.empty()){//栈不为空ListNode *temp = new ListNode(s.top());//取栈顶元素放入链表s.pop();//弹出栈顶元素last->next = temp;last = temp;}return res->next;}
};