Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cmath>
- #include <cstdio>
- #include <vector>
- #include <iostream>
- #include <algorithm>
- using namespace std;
- class ListNode {
- public:
- ListNode* next;
- int val;
- ListNode() : val(0), next(nullptr) {}
- ListNode(int val) : val(val), next(nullptr) {}
- ~ListNode() {
- if (next) {
- delete next;
- }
- }
- };
- ListNode* swapPairs(ListNode* head) {
- // TODO: implementati functia ce interschimba nodurile doua cate doua.
- ListNode* temp = head;
- ListNode* prev;
- ListNode* temp1;
- if (temp != NULL && temp->next != NULL) {
- temp1 = temp->next;
- temp->next = temp1->next;
- temp1->next = temp;
- prev = temp;
- temp = temp->next;
- head = temp1;
- }
- while (temp != NULL && temp->next != NULL) {
- temp1 = temp->next;
- temp->next = temp1->next;
- temp1->next = temp;
- prev->next = temp1;
- prev = temp;
- temp = temp->next;
- }
- return head;
- }
- int main() {
- int n;
- // TODO: Form the list and call swapPairs
- cin >> n;
- int x;
- cin >> x;
- ListNode* res = new ListNode(x);
- ListNode* it = res;
- for (int i = 1; i < n; i++) {
- cin >> x;
- ListNode* tmp = new ListNode(x);
- it->next = tmp;
- it = tmp;
- }
- res = swapPairs(res);
- for (int i = 0; i < n; ++i) {
- cout << res->val << " ";
- res = res->next;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement