[LeetCode]Swap Nodes in Pairs
来源:互联网 发布:windows重置此电脑失败 编辑:程序博客网 时间:2024/05/29 04:22
题目
Number: 24
Difficulty: Medium
Tags: Linked List
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.
题解
链表中每两个结点交换。
不允许改变值。比较简单,注意边界处理。
代码
非递归:
ListNode* swapPairs(ListNode* head) { ListNode* p = head; ListNode* pre = p; if(!p) return head; while(p && p->next) { ListNode* q = p->next; p->next = q->next; q->next = p; if(p == head) head = q; else pre->next = q; pre = p; p = p->next; } return head;}
递归:
ListNode* swapPairs(ListNode* head) { ListNode* p = head; if(!p || !p->next) return head; p = head->next; head->next = swapPairs(p->next); p->next = head; return p;}
0 0
- LeetCode: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: 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 | 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: Swap Nodes in Pairs
- Leetcode Swap Nodes in Pairs
- LeetCode Swap Nodes in Pairs
- 2.2.3 Main方法;2.2.4 标识符及关键字;2.2.5 C#语句
- 【LeetCode-面试算法经典-Java实现】【098-Validate Binary Search Tree(验证二叉搜索树)】
- linux下logrotate 配置和理解
- oc语言第九课 KVC、KVO与谓词——ios学习连载14
- [LeetCode]Generate Parentheses
- [LeetCode]Swap Nodes in Pairs
- [LeetCode]Divide Two Integers
- UI初级第一课 iPhone开发入门——iOS学习连载15
- jquery.artDialog.source.js学习
- H3C simware模拟器(解决不能tab/?)
- JDBC学习笔记
- 七个免费的Linux FTP客户端--转自51CTO
- 堆栈溢出攻击原理
- 天声人語 20150806