LeetCode Swap Nodes in Pairs

链接:https://oj.leetcode.com/problems/swap-nodes-in-pairs/


交换链表相邻的节点的位置

/**
 * 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)
		{
			ListNode *ans=new ListNode(0);
			ans->next=head;
			head=ans;					//添加哨兵
			if(ans->next==NULL||ans->next->next==NULL)
			    return ans->next;
			ans=ans->next->next;
			while(head->next&&head->next->next)
			{
				ListNode *last=head->next->next;	
				head->next->next=last->next;
				last->next=head->next;
				head->next=last;
				head=last->next;
			}
			return ans;
		}
};


原文地址:https://www.cnblogs.com/frankM/p/4399438.html