[LeetCode] 24. Swap Nodes in the Linked List Pairwise (C++)

Original title address: https://leetcode-cn.com/problems/swap-nodes-in-pairs/description/

Topic description:

Given a linked list, swap adjacent nodes two by two, and return the swapped linked list.

Example:

Given 1->2->3->4, you should return 2->1->4->3.

illustrate:

  • Your algorithm can only use constant extra space.
  • You can't just change the value inside the node , you need to actually do the node swap.

Problem solving method:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        ListNode* pre;
        ListNode* p = head;
        ListNode* q ;
        if(!p) return NULL;
        if(!p->next)    return head;
        q = p->next;
        pre = q;
        head = pre;
        p->next = q->next;
        q->next = p;
        pre = pre->next;
        while(1){
            p = p->next;
            if(!p)   break;
            q = p->next;
            if(!q)   break;
            p->next = q->next;
            q->next = p;
            pre->next = q;
            pre = pre->next->next;
        }
        return head;
    }
};

In fact, it is the operation of pointers, regular questions.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324759358&siteId=291194637