LeetCode Swap Nodes in Pairs
2014-06-03 21:48
148 查看
class Solution { public: ListNode *swapPairs(ListNode *head) { ListNode *a = NULL; ListNode *b = NULL; ListNode *tail = NULL; ListNode *nhead = NULL; a = head; while (a != NULL && (b = a->next) != NULL) { a->next = b->next; b->next = a; if (tail != NULL) { tail->next = b; } else { nhead = b; } tail = a; a = a->next; } if (nhead == NULL) { nhead = head; } return nhead; } };
准备六级,水一发
第二轮:
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.
class Solution { public: ListNode *swapPairs(ListNode *head) { if (head == NULL || head->next == NULL) { return head; } ListNode holder(0); ListNode* prev = &holder; ListNode* cur = head; while (cur != NULL) { ListNode* next = cur->next; if (next == NULL) { break; } head = next->next; next->next = cur; cur->next = head; prev->next = next; prev = cur; cur = cur->next; } return holder.next; } };
相关文章推荐
- [leetcode刷题系列]Swap Nodes in Pairs
- [leetcode]Swap Nodes in Pairs
- [LeetCode] Swap Nodes in Pairs
- [LeetCode] Swap Nodes in Pairs、Reverse Nodes in k-Group、Rotate List
- leetcode -- Swap Nodes in Pairs
- LeetCode: Swap Nodes in Pairs
- LeetCode_Swap Nodes in Pairs
- LeetCode:Swap Nodes in Pairs
- leetcode 49: Swap Nodes in Pairs
- leetcode之Swap Nodes in Pairs
- LeetCode-Swap Nodes in Pairs
- LeetCode : Swap Nodes in Pairs
- [Leetcode] Swap Nodes in Pairs
- leetcode 49: Swap Nodes in Pairs
- [LeetCode] Swap Nodes in Pairs 解题报告
- LeetCode Online Judge 题目C# 练习 - Swap Nodes in Pairs
- 【LeetCode with Python】 Swap Nodes in Pairs
- leetcode 14: Swap Nodes in Pairs
- leetcode—Swap Nodes in Pairs
- LeetCode - Swap Nodes in Pairs