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 24 Swap Nodes in Pairs
- LeetCode 24.Swap Nodes in Pairs
- Java [leetcode 24]Swap Nodes in Pairs
- Leetcode_24_Swap Nodes in Pairs
- leetcode 24 -- Swap Nodes in Pairs
- [LeetCode]24 Swap Nodes in Pairs
- LeetCode 24 Swap Nodes in Pairs (C,C++,Java,Python)
- Leetcode 24 Swap Nodes in Pairs
- LeetCode 24:Swap Nodes in Pairs
- leetcode_24_Swap Nodes in Pairs
- leetcode 24 Swap Nodes in Pairs
- [leetcode 24]Swap Nodes in Pairs
- Swap Nodes in Pairs - LeetCode 24
- LeetCode24之SwapNodesInPairs的Java 题解
- [Leetcode 22] 24 Swap Nodes in Pairs
- [Leetcode] 24. Swap Nodes in Pairs
- [leetcode 24] Swap Nodes in Pairs
- LeetCode 24 - Swap Nodes in Pairs
- leetcode-24 Swap Nodes in Pairs
- LeetCode_24---Swap Nodes in Pairs