#include <iostream>
struct Node
{
int data;
Node *next;
};
Node* push(Node *head, const int i)
{
Node *elem = new Node;
elem->data = i;
if (!head)
elem->next = nullptr;
else
elem->next = head;
return elem;
}
void print(Node *head)
{
while (head)
{
std::cout << head->data << " ";
head = head->next;
}
}
Node* reverse(Node *head)
{
if(head == nullptr)
return nullptr;
Node *prev = nullptr;
while(head->next != nullptr)
{
Node *next = head->next;
head->next = prev;
prev = head;
head = next;
}
head->next = prev;
return head;
}
int main() {
Node *list = nullptr;
for (int i = 0; i < 4; ++i)
list = push (list, i);
print (list);
std::cout << std::endl;
list = reverse (list);
print (list);
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgoKc3RydWN0IE5vZGUKewoJaW50IGRhdGE7CglOb2RlICpuZXh0Owp9OwoKTm9kZSogcHVzaChOb2RlICpoZWFkLCBjb25zdCBpbnQgaSkKewoJTm9kZSAqZWxlbSA9IG5ldyBOb2RlOwoJZWxlbS0+ZGF0YSA9IGk7CgkKCWlmICghaGVhZCkKCQllbGVtLT5uZXh0ID0gbnVsbHB0cjsKCWVsc2UKCQllbGVtLT5uZXh0ID0gaGVhZDsKCXJldHVybiBlbGVtOwp9Cgp2b2lkIHByaW50KE5vZGUgKmhlYWQpCnsKCXdoaWxlIChoZWFkKQoJewoJCXN0ZDo6Y291dCA8PCBoZWFkLT5kYXRhIDw8ICIgIjsKCQloZWFkID0gaGVhZC0+bmV4dDsKCX0KfQoKTm9kZSogcmV2ZXJzZShOb2RlICpoZWFkKQp7CiAgICBpZihoZWFkID09IG51bGxwdHIpCiAgICAgICAgcmV0dXJuIG51bGxwdHI7CiAgICBOb2RlICpwcmV2ID0gbnVsbHB0cjsKICAgIHdoaWxlKGhlYWQtPm5leHQgIT0gbnVsbHB0cikKICAgIHsKICAgICAgICBOb2RlICpuZXh0ID0gaGVhZC0+bmV4dDsKICAgICAgICBoZWFkLT5uZXh0ID0gcHJldjsKICAgICAgICBwcmV2ID0gaGVhZDsKICAgICAgICBoZWFkID0gb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