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.

分析与解答:

交换链表中相邻的节点。依然是链表的题目,考察对链表操作的熟练程度,交换两个相邻的链表需要三个指针,要清晰地知道各种指针是怎么来回变换的,注意逻辑判断时要包含链表节点数为奇数和链表为空的情况即可。

/**
 * 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 *p1, *p2, *p, *result;
	result = p = new ListNode(0);
	p->next = head;
	while (p->next != NULL && p->next->next != NULL) {
		p1 = p->next->next;
		p2 = p->next;
		p->next = p1;
		p2->next = p1->next;
		p1->next = p2;
		p = p->next->next;
	}
	return result->next;
}
};


你可能感兴趣的:(list,linked)