力扣原题:反转链表
#include<stdio.h>
#include<iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
ListNode* reverseList(ListNode* head) {
if (head == nullptr) return nullptr;
ListNode* pre = nullptr;
ListNode* cur = head;
while (cur->next != nullptr) {
ListNode* tmp = cur->next;
cur->next = pre;
pre = cur;
cur = tmp;
}
cur->next = pre;
return cur;
}
void PrintList(ListNode* head) {
if (head == NULL) {
std::cout << "NULL" << std::endl;
return;
}
ListNode* cur = head;
while (cur != NULL) {
std::cout << cur->val << "->";
cur = cur->next;
}
std::cout << "NULL" << std::endl;
}
int main() {
ListNode* n1 = new ListNode(1);
ListNode* n2 = new ListNode(2);
ListNode* n3 = new ListNode(3);
ListNode* n4 = new ListNode(4);
n1->next = n2;
n2->next = n3;
n3->next = n4;
PrintList(n1);
PrintList(reverseList(n1));
}
注意点:当cur节点遍历到最后一个有效节点的时候,不能再使cur=tmp;因为此时tmp为NULL