题意:实现链表的反转
#include<iostream>
#include<stack>
using namespace std;
// 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) {
if (!head) return head;
if (!head->next) return head;
stack<ListNode*> stack;
while (head)
{
stack.push(head);
head = head->next;
}
ListNode* result, * temp;
result = stack.top();
temp = result;
temp->next = nullptr;
stack.pop();
while (!stack.empty())
{
temp->next = stack.top();
temp = temp->next;
stack.pop();
}
temp->next = nullptr;
return result;
}
};
//方法二:递归法
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (!head) return head;
if (!head->next) return head;
ListNode* result, * temp;
recursion(head, result, temp);
temp->next = nullptr;
return result;
}
void recursion(ListNode* ptr, ListNode* result, ListNode* temp) {
if (!ptr->next)
{
result = ptr;
temp = result;
}
recursion(ptr->next, result, temp);
temp->next = ptr;
temp = temp->next;
}
};
//方法三:网友方法,创建新链表的同时,给出指针变量的指向
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* c = head;
ListNode* reverse = new ListNode();
ListNode* c2 = reverse;
if (c != NULL)
reverse->val = c->val;
else
return NULL;
while (c->next != NULL) {
ListNode* newNode = new ListNode(c->next->val, reverse);
c = c->next;
reverse = newNode;
}
return reverse;
}
};