【C++】【LeetCode】24. Swap Nodes in Pairs

来源:互联网 发布:淘宝怎么交电费 编辑:程序博客网 时间:2024/06/04 18:46

题目

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个结点,则交换两个结点,然后继续往下判断接下来两个结点是否为NULL。
注意:使用 && 时,当前者不满足条件,不执行后者,不会发生NULL->next,所以不会出错。

代码

/** * 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 *tmpPre;        if (head == NULL) {            return head;        } else if (head->next == NULL) {            return head;        } else {            ListNode *tmp = head;            head = head->next;            tmp->next = head->next;            head->next = tmp;            tmpPre = head->next;         }        while (tmpPre->next != NULL && tmpPre->next->next != NULL) {            ListNode *tmp = tmpPre->next;            tmpPre->next = tmpPre->next->next;            tmp->next = tmpPre->next->next;            tmpPre->next->next = tmp;            tmpPre = tmpPre->next->next;        }        return head;    }};
原创粉丝点击