#include<iostream>
using namespace std;
#include<vector>
class ListNode
{
public:
int data; //数据域
ListNode* next; //指针域
ListNode(int x):data(x),next(NULL){}
};
//输入处理
vector<int> inputV()
{
int n;
cout << "请输入链表元素的个数" << endl;
cin >> n;
vector<int> nums;
cout << "请输入" << n << "个数";
cout << endl;
for (int i = 0; i<n; i++)
{
int temp;
cin >> temp;
nums.push_back(temp);
}
return nums;
}
//创建链表
ListNode* creat(vector<int>& nums)
{
//创建头节点
ListNode* head = NULL;
head = new ListNode(0);
ListNode* p = head; //记录头指针
for (auto it: nums.end())
{
ListNode* pNewNode = new ListNode(*it);//创建新结点
p->next = pNewNode; //上个节点指针域放新节点的地址
p = pNewNode;//更新结点
}
return head;
}
//链表反转 head -> 1 -> 2 -> 3 -> 4 -> 5 ->NULL
// NULL <- 1 -> 2 -> 3 -> 4 -> 5 ->NULL
// NULL <- 1 <- 2 -> 3 -> 4 -> 5 ->NULL
ListNode* reverseList(ListNode* head)
{
ListNode* pre = NULL;
ListNode* p = head;
while (p)
{
ListNode* next = p->next; //记录下一个结点
p->next = pre;
pre = p;
p = next;
}
return pre;
}
//打印链表
void printLi(ListNode* L) //传入头指针,利用头指针可找到整个链表
{
while (L->next !=NULL)
{
cout << L->data << " ";
L = L->next;
}
cout << endl;
}
int main()
{
vector<int> nums;
nums = inputV(); //inputNum()用户输入一组数字,保存在vector中
ListNode* head = NULL;
head = creat(nums);
head = reverseList(head);
printLi(head);
system("pause");
return 0;
}