题目:
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.
思路:
- 设p,q两个指针分别指向要交换的结点,交换p和q的指针p->next = q->next;q->next = p;
- 设tmp为已经交换的链表的最后一个结点。
- 注意判断结点是否为空。:)
C++代码如下:
ListNode* swapPairs(ListNode* head) {
if (head == NULL || head->next == NULL)
return head;
ListNode* p = head;
ListNode* q = head->next;
ListNode* phead = q;
while (p != NULL && q != NULL)
{
p->next = q->next;
q->next = p;
ListNode* tmp = p;
if (p->next != NULL && p->next->next != NULL)
{
p = p->next;
q = p->next;
tmp->next = q;
}
else
return phead;
}
}