您的位置:首页 > Web前端 > Node.js

Leetcode -- 24. Swap Nodes in Pairs

2017-04-20 23:29 501 查看

题目:

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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode c-c++