Last active
January 25, 2025 14:20
-
-
Save OriLiMu/eb51d7ac210668fb2dfff28633eb35c9 to your computer and use it in GitHub Desktop.
ReverseChainList
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstddef> | |
#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 *reverseChainList(ListNode *head) { | |
if (!head) | |
return head; | |
ListNode *prev = nullptr; | |
ListNode *cur = head; | |
ListNode *next = nullptr; | |
while (cur) { | |
next = cur->next; | |
cur->next = prev; | |
prev = cur; | |
cur = next; | |
} | |
return prev; | |
} | |
int main(int argc, char *argv[]) { | |
ListNode *head = new ListNode( | |
1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5))))); | |
ListNode *result = reverseChainList(head); | |
while (result) { | |
cout << result->val << " "; | |
result = result->next; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment