9.反转链表
题目内容:
代码及思路:
#include<iostream>
using namespace std;
struct Linklist
{
int val;
Linklist* next;
};
class solution
{
public:
Linklist* buildlist()
{
int num;
Linklist* p1 = nullptr;
Linklist* p2 = nullptr;
Linklist* head = nullptr;
char ch;
do
{
cin >> num;
p1 = new Linklist;
p1->val = num;
if (head == nullptr)
head = p1;
else
p2->next = p1;
p2 = p1;
cin.get(ch);
} while (ch == ',');
if (head == nullptr)
return nullptr;
p2->next = nullptr;
return head;
}
Linklist* Reverselist(Linklist* head)
{
if (head == nullptr)
return nullptr;
Linklist* newhead = nullptr;
while (head != nullptr)
{
Linklist* temp = head->next;
head->next = newhead;
newhead = head;
head = temp;
}
return newhead;
}
};
void main()
{
solution* object = new solution();
Linklist* head=object->buildlist();
Linklist* res = object->Reverselist(head);
Linklist* newhead = res;
while (newhead != nullptr)
{
cout << newhead->val << endl;
newhead = newhead->next;
}
}