递归构造链表+反转链表
注意事项:
1、使用getline(cin,s)获取一整行的带空格的字符串
2、链表循环条件while(cur&&cur->next)
3、//1 2 3 出循环时,cur的位置在链表最后一个非空节点,此时cur->next指向nullptr,需要增加一行,将cur->next=tmp2;
#include<iostream>
#include<vector>
#include<string>
using namespace std;
//创建LIstNode结构体
struct ListNode {
int val;
ListNode* next;
ListNode(int val, ListNode* next):next(next),val(val){}
};
//递归创建链表
ListNode* ListBuild(vector<int> &v, int index) {
ListNode* nextNode = nullptr;
if (index +1< v.size()) nextNode = ListBuild(v, index + 1);
ListNode* head = new ListNode(v[index], nextNode);
return head;
}
int main() {
string s;
getline(cin, s);
vector<int> v;
//字符处理
for (int i = 0; i < s.size(); ) {
while (i < s.size() && s[i] == ' ') i++;
string st;
while (i < s.size() && s[i] != ' ') {
st += s[i];
i++;
}
if (!st.empty()) v.push_back(stoi(st));
}
ListNode* Node = ListBuild(v,0);
//反转链表
ListNode* cur = Node;
ListNode* tmp1;
ListNode* tmp2 = nullptr;
while (cur&&cur->next) {
tmp1 = cur->next;
cur->next = tmp2;
tmp2 = cur;
cur = tmp1;
}
cur->next = tmp2;//注意最后一个节点的->next在循环体内未修改
while (cur) {
cout << cur->val << " ";
cur = cur->next;
}
//tmp1->next = cur;
//cur = tmp1;
// 1 2 3
return 0;
}
2021/11/2 又复写了一遍 ,顺多了,希望以后能写得再顺利一点。
while (1) {
tmp1 = cur->next;
cur->next = tmp2;
tmp2 = cur;
if (tmp1) cur = tmp1;
else break;
}