LeetCode Swap Nodes in Pairs

题目

Given a linked list, swapevery 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 useonly constant space. You may not modify the values in the list, onlynodes itself can be changed.

 

要求常数空间,不能更改值。

每两个元素为单位向后推,记录之前调整后元素的后者,保存后继。

 

代码:

/**
 * 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 *p1=head,*p2=p1->next,*p_pro=NULL,*p_next;	//每两个元素的前、后,之前2个元素调整后的后者,未调整的之后的元素
		head=p2;
		while(p2!=NULL)
		{
			if(p_pro!=NULL)
				p_pro->next=p2;
			p_next=p2->next;
			p2->next=p1;
			p_pro=p1;
			p_pro->next=p_next;
			p1=p_next;
			if(p_next!=NULL)
				p2=p1->next;
			else
				break;
		}
		return  head;
    }
};


 

 

 

你可能感兴趣的:(LeetCode,C++,算法)