本文采用改变next指针指向的方法就地逆置;
也可采用头插法就地逆置。
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <vector>
using namespace std;
typedef struct ListNode {
int val;
struct ListNode* next;
ListNode(int x) :
val(x), next(NULL) {
}
}ListNode;
void printArr(vector<int> Arr)
{
for (vector<int>::iterator it = Arr.begin(); it != Arr.end() - 1; it++)
{
cout << *it << " ";
}
cout << endl;
}
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> ArrayList;
while (head != NULL)
{
ArrayList.push_back(head->val);
head = head->next;
}
reverse(ArrayList.begin(), ArrayList.end());
printArr(ArrayList);
return ArrayList;
}
};
int main()
{
ListNode* head = NULL;
head = (ListNode*)malloc(sizeof(ListNode));
ListNode* pCur = head;
ListNode* pNew = NULL;
int data;
while (1) {
printf("请输入数据: ");
scanf("%d", &data);
if (data == -1)
break;
pNew = (ListNode*)malloc(sizeof(ListNode));
pNew->val = data;
pNew->next = NULL;
pCur->next = pNew;
pCur = pNew;
}
Solution s;
s.printListFromTailToHead(head);
return 0;
}