Advertisement
Guest User

Untitled

a guest
Feb 27th, 2020
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.76 KB | None | 0 0
  1. /**
  2.  * Definition for singly-linked list.
  3.  * struct ListNode {
  4.  *     int val;
  5.  *     ListNode *next;
  6.  *     ListNode(int x) : val(x), next(NULL) {}
  7.  * };
  8.  */
  9.  
  10. void swap(ListNode* A, ListNode* B, ListNode* C, ListNode* last){
  11.     A->next = C;
  12.     B->next = A;
  13.     last->next = B;
  14. }
  15.  
  16. ListNode* solve(ListNode* input){
  17.     ListNode *last = new ListNode(0);
  18.     ListNode *ans = last;
  19.     ListNode *A, *B, *C;
  20.     last->next = input;
  21.     while(last->next != NULL and last->next->next != NULL){
  22.         A = last->next;
  23.         B = A->next;
  24.         C = B->next;
  25.         swap(A, B, C, last);
  26.         last = A;
  27.     }
  28.     return ans->next;
  29. }
  30. ListNode* Solution::swapPairs(ListNode* A) {
  31.     if(A == NULL or A->next == NULL) return A;
  32.     return solve(A);
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement