链表反转 C++ 版本 leetcode206
(原题网址)[https://leetcode.com/problems/reverse-linked-list/description/]
给出我的解答
#include <iostream>
using namespace std;
//Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
explicit ListNode(int x) : val(x), next(nullptr) {}
};
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (head == nullptr){
return head;
}
else if(head->next == nullptr){
return head;
}
ListNode* prev = nullptr;
ListNode* curr;
while(head != nullptr){
curr = head;
head = head->next;
curr->next = prev;
prev = curr;
}
return prev;
}
};
并附上测试代码:
int main() {
std::cout << "Hello, World!" << std::endl;
ListNode n1(0);
ListNode n2(2);
ListNode n3(5);
ListNode n4(7);
ListNode n5(10);
n1.next = &n2;
n2.next = &n3;
n3.next = &n4;
n4.next = &n5;
// 遍历一个链表
ListNode* head = &n1;
while(head){
cout << head->val << ' ';
head = head->next;
}
Solution so;
so.reverseList(&n1);
cout << endl;
head = &n5;
while(head){
cout << head->val << ' ';
head = head->next;
}
return 0;
}