LeetCode 24:Swap Nodes in Pairs

1549 ワード

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.
この問題はLeetCode 25 Reverse Nodes in k-Groupの特殊な状況であるK=2である.LeetCode 25の解法は以下の通りです.http://blog.csdn.net/sunao2002002/article/details/46416977.したがって、本題のコードは以下の通りです.
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    int getListSize(ListNode* head)
	{
		int count = 0;
		while (head)
		{
			head = head->next;
			count++;
		}
		return count;
	}

	ListNode* addHead(ListNode*head, ListNode*Node)
	{
		Node->next = head;
		return Node;
	}
	ListNode* reverseKGroup(ListNode* head, int k) {
		int length = getListSize(head);
		ListNode tmpHead(-1);
		ListNode *pNode = &tmpHead;
		while(length >= k){
			ListNode* pHead = NULL;
			for (int i=0; i<k; i++)
			{
				ListNode*ptmpNode = head;
				head = head->next;
				ptmpNode->next = NULL;
				pHead = addHead(pHead, ptmpNode);
			}
			pNode->next = pHead;
			while(pNode->next)
				pNode = pNode->next;
			length -= k;
		}
		pNode->next = head;
		return tmpHead.next;
	}
    ListNode* swapPairs(ListNode* head) {
        return reverseKGroup(head, 2);
        
    }
};