【算法设计与分析作业题】第十五周:24. Swap Nodes in Pairs

题目

C++ solution

/**
 * 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) {
        if (head == NULL || head->next == NULL)
        	return head;
        ListNode* first = head;
        ListNode* second = head->next;
        first->next = second->next;
        second->next = first;
        head = second;
        ListNode* last = first;
        first = first->next;
        if (first == NULL)
        	return head;
        second = first->next;
        while (second != NULL) {
        	first->next = second->next;
        	second->next = first;
        	last->next = second;
        	last = first;
        	first = first->next;
        	if (first == NULL)
        		break;
        	second = first->next;
        }
        return head;
    }
};

简要题解

按链表顺序交换每两个结点的位置,仔细进行指针操作,注意指针越界问题,即可求解。

猜你喜欢

转载自blog.csdn.net/For_course/article/details/84960133