Advertisement
Guest User

Interschimbare

a guest
Aug 24th, 2019
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. #include <cmath>
  2. #include <cstdio>
  3. #include <vector>
  4. #include <iostream>
  5. #include <algorithm>
  6. using namespace std;
  7. class ListNode {
  8. public:
  9. ListNode* next;
  10. int val;
  11. ListNode() : val(0), next(nullptr) {}
  12. ListNode(int val) : val(val), next(nullptr) {}
  13. ~ListNode() {
  14. if (next) {
  15. delete next;
  16. }
  17. }
  18. };
  19.  
  20. ListNode* swapPairs(ListNode* head) {
  21. // TODO: implementati functia ce interschimba nodurile doua cate doua.
  22. ListNode* temp = head;
  23. ListNode* prev;
  24. ListNode* temp1;
  25. if (temp != NULL && temp->next != NULL) {
  26. temp1 = temp->next;
  27. temp->next = temp1->next;
  28. temp1->next = temp;
  29. prev = temp;
  30. temp = temp->next;
  31. head = temp1;
  32. }
  33. while (temp != NULL && temp->next != NULL) {
  34. temp1 = temp->next;
  35. temp->next = temp1->next;
  36. temp1->next = temp;
  37. prev->next = temp1;
  38. prev = temp;
  39. temp = temp->next;
  40. }
  41. return head;
  42. }
  43.  
  44. int main() {
  45. int n;
  46. // TODO: Form the list and call swapPairs
  47. cin >> n;
  48. int x;
  49. cin >> x;
  50. ListNode* res = new ListNode(x);
  51. ListNode* it = res;
  52. for (int i = 1; i < n; i++) {
  53. cin >> x;
  54. ListNode* tmp = new ListNode(x);
  55. it->next = tmp;
  56. it = tmp;
  57. }
  58. res = swapPairs(res);
  59. for (int i = 0; i < n; ++i) {
  60. cout << res->val << " ";
  61. res = res->next;
  62. }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement