LeetCode 24: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.

此题是LeetCode 25 Reverse Nodes in k-Group的一种特殊情况,即K=2. LeetCode25的解法请参考: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);
        
    }
};


你可能感兴趣的:(LeetCode)