leetcode 24 -- Swap Nodes in Pairs

Swap Nodes in Pairs

题目:
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify the
values in the list, only nodes itself can be changed.


题意:
给你一个链表,交换两两节点,要求不能交换值,必须改变指针。
1->2->3->4 变为 2->1->4->3


思路:
注意保存pre先前的指针,还要注意特殊情况,有0个或者1个节点。以及链表长度为奇数的情况。


代码:

/**
 * 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) {
        //特殊情况,0个或1个节点
        if(head == NULL || head->next == NULL){
            return head;
        }
        ListNode *p = head;
        ListNode *q = head->next;
        //两个节点的情况
        if(q->next == NULL){
            q->next = p;
            p->next = NULL;
            head = q;
            return head;
        }
        ListNode *nextNode = q->next;
        ListNode *pre;
        head = q;
        while(q != NULL && nextNode != NULL){
            //改变指针指向
            pre = p;
            q->next = p;
            p->next = nextNode;
            //向前跳转
            q = nextNode->next;
            if(q == NULL){
                break;
            }
            p = nextNode;
            nextNode = q->next;
            pre->next = q;
        }
        //处理奇数节点的情况
        if(nextNode == NULL){
            pre->next = q;
            q->next = p;
            p->next = NULL;
        }
        return head;
    }
};
原文地址:https://www.cnblogs.com/mfrbuaa/p/5081764.html