自以为简单的算法一定要写出来运行后没问题才敢说简单,动脑不如动手!
#include <iostream>
#include <vector>
using namespace std;
struct ListNode{
int val;
ListNode *next;
ListNode(int v):val(v),next(nullptr){};
}
//链表倒置 返回倒置后的根节点
ListNode* ReverseList(ListNode *root){
if(!root) return nullptr;
ListNode *pre = root;
ListNode *cur = root->next;
root->next = nullptr; //在保存传入根节点root的next节点后将root节点的next指针置零,否则会没有尾节点 并形成回环
while(cur){
ListNode *temp = cur->next;//先保存后面节点地址
cur->next = pre;
pre = cur;
cur = temp;
}
return pre;
}
//从头到尾打印链表
bool PrintList(ListNode *root,vector<int> &arr){
if(!root) {
arr.clear();
return false;
}
while(root){
arr.push_back(root->val);
cout<<root->val<<'-';
root = root->next;
}
cout<<"end"<<endl;
}
int main(){
ListNode *pre,*cur;
pre = new ListNode(0);
ListNode *root = pre; //保存根节点
for(int i=1;i<5;i++){
cur = new ListNode(i);
pre->next = cur;
pre = cur;
}
vector<int> arr;
PrintList(root,arr);
ListNode *Revroot=ReverseList(root);
PrintList(Revroot,arr);
return 0;
}