LeetCode刷题笔记(链表):swap-nodes-in-pairs
2018-01-22 11:10
387 查看
转载请注明作者和出处:http://blog.csdn.net/u011475210
代码地址:https://github.com/WordZzzz/Note/tree/master/LeetCode
刷题平台:https://www.nowcoder.com/ta/leetcode
题 库:Leetcode经典编程题
编 者:WordZzzz
题目描述
解题思路
C版代码实现
For example,
Given1->2->3->4, you should return the list as2->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.
系列教程持续发布中,欢迎订阅、关注、收藏、评论、点赞哦~~( ̄▽ ̄~)~
完的汪(∪。∪)。。。zzz
代码地址:https://github.com/WordZzzz/Note/tree/master/LeetCode
刷题平台:https://www.nowcoder.com/ta/leetcode
题 库:Leetcode经典编程题
编 者:WordZzzz
题目描述
解题思路
C版代码实现
题目描述
Given a linked list, swap every two adjacent nodes and return its head.For example,
Given1->2->3->4, you should return the list as2->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.
解题思路
通过这么多次的编程练习,链表的顺序交换我相信大家早已轻车熟路。本题中,我们先写一个交换相邻结点的函数swap,此函数交换输入的两个相邻链表结点之后,返回新的第一结点。然后我们开始考虑主函数,同样的新建一个指向头结点的指针(只要头结点有可能被替换,我们既需要这么做),然后遍历整个链表调用交换函数swap即可。C++版代码实现
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *swap(ListNode *slow, ListNode *fast){ slow->next = fast->next; fast->next = slow; return fast; } ListNode *swapPairs(ListNode *head) { if(head == NULL || head->next == NULL) return head; ListNode *dummy = new ListNode(0); dummy->next = head; ListNode *cur = dummy; for(;cur->next != NULL && cur->next->next != NULL; cur = cur->next->next) cur->next = swap(cur->next, cur->next->next); return dummy->next; } };
系列教程持续发布中,欢迎订阅、关注、收藏、评论、点赞哦~~( ̄▽ ̄~)~
完的汪(∪。∪)。。。zzz
相关文章推荐
- leetcode之24. Swap Nodes in Pairs(C++实现&链表实现和整体测试)
- LeetCode_链表操作1—Swap Nodes in Pairs
- [Leetcode 24 链表]Swap Nodes in Pairs
- LeetCode笔记:24. Swap Nodes in Pairs
- LeetCode_链表操作1—Swap Nodes in Pairs
- LeetCode-24-Swap-Nodes-in-Pairs 链表递归水题
- [leetcode] 24 Swap Nodes in Pairs(交换链表相邻结点)
- Swap Nodes in Pairs 链表两两交换节点@LeetCode
- leetCode 24. Swap Nodes in Pairs 链表
- 【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笔记--Swap Nodes in Pairs
- LeetCode - 24 - Swap Nodes in Pairs(交换链表结点)
- 【leetcode】【单链表】【24】Swap Nodes in Pairs
- [leetcode] 【链表】24. Swap Nodes in Pairs
- Leetcode:Swap Nodes in Pairs 单链表相邻两节点逆置
- LeetCode 24 Swap Nodes in Pairs (链表 递归&&非递归)
- leetcode 24. Swap Nodes in Pairs(链表)