LeetCode Swap Nodes in Pairs

1.题目

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.


2.解决方案


class Solution {
public:
   
    ListNode *swapPairs(ListNode *head) {
       ListNode* returnNode  = head;

	ListNode* preNode = NULL;
	while(head != NULL && head->next != NULL){
		ListNode* firstNode = head;
		ListNode* secondNode = head->next;

		if(preNode != NULL){//first node
			preNode->next = secondNode;
		}else{
			if(secondNode != NULL){
				returnNode = secondNode;
			}
		}
		firstNode->next = secondNode->next;
		secondNode->next = firstNode;


		preNode = head;
		head = head->next;
	}

	return returnNode;

    }
};

思路:这题还是比较简单的。while循环,交换两个指针而已。但要注意细节以及返回的值。


http://www.waitingfy.com/archives/1583


你可能感兴趣的:(LeetCode Swap Nodes in Pairs)