链表 Swap Nodes in Pairs
2015-04-09 16:54
253 查看
思想:
创建一个辅助头结点简便编程。
下一轮swap中若first为NULL,则second直接设为NULL。
创建一个辅助头结点简便编程。
下一轮swap中若first为NULL,则second直接设为NULL。
/** * 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) { if(head == NULL || head->next == NULL) // at least two nodes, if not, return return head; ListNode *dummy = new ListNode(-1); dummy->next = head; ListNode *prev,*first,*second; prev = dummy; first = prev->next; second = first->next; while(second != NULL) { prev->next = second; first->next = second->next; second->next = first; prev = first; first = first->next; second = (first == NULL ? NULL : first->next); } return dummy->next; } };
相关文章推荐
- Swap Nodes in Pairs 链表交换相邻的节点
- leetcode---swap-nodes-in-pairs---链表
- LeetCode_链表操作1—Swap Nodes in Pairs
- 【leetcode】【单链表】【24】Swap Nodes in Pairs
- 451. 两两交换链表中的节点(swap-nodes-in-pairs)(c++)----lintcode面试题之链表
- [leetcode] 【链表】24. Swap Nodes in Pairs
- 【leetcode】【单链表】【24】Swap Nodes in Pairs
- swap-nodes-in-pairs(单链表交换点对)
- Leetcode:Swap Nodes in Pairs 单链表相邻两节点逆置
- LeetCode-24-Swap Nodes in Pairs(链表)-Medium
- LeetCode-24 Swap Nodes in Pairs(链表中按要求交换节点)
- [leetcode] 24 Swap Nodes in Pairs(交换链表相邻结点)
- Swap Nodes in Pairs(交换链表相邻的两个结点)
- [LeetCode][链表]Swap Nodes in Pairs
- leetCode 24. Swap Nodes in Pairs 链表
- [Leetcode 24 链表]Swap Nodes in Pairs
- LeetCode刷题笔记(链表):swap-nodes-in-pairs
- Swap Nodes in Pairs 链表两两交换节点@LeetCode
- leetcode #24 swap nodes in pairs 链表
- leetcode之24. Swap Nodes in Pairs(C++实现&链表实现和整体测试)