24. Swap Nodes in Pairs leetcode(list)
来源:互联网 发布:报表汇总软件 编辑:程序博客网 时间:2024/05/04 19:17
- Swap Nodes in Pairs
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.
方法一、递归的解法
ListNode* swapPairs(ListNode* head) { if(head == NULL || head->next == NULL) return head; ListNode* newHead = head->next; head->next = swapPairs(head->next->next); newHead->next = head; return newHead; }
方法二、非递归的解法
ListNode* swapPairs(ListNode* head) { if(NULL == head || NULL == head->next) { return head; } ListNode* first = head; ListNode* second = first->next; ListNode* pre; int count = 0; while(first && second) { first->next = second->next; second->next = first; if(count == 0) //如果是最开始的两个节点,则需要更改头节点 { head = second; } else //如果不是开始的两个节点,则在交换第二个节点时,需要将第二个节点插在上一轮交换的最后一个节点之后,用pre保存 { pre->next = second; } pre = first; //更新pre节点 first = first->next; if(first) //注意如果first已经为NULL了,如果不加入if判断则会出现runtime 的错误 { second = first->next; } count++; } return head; }
0 0
- 24. Swap Nodes in Pairs leetcode(list)
- [leetcode][list] Swap Nodes in Pairs
- 24. Swap Nodes in Pairs(Linked List)
- [LeetCode]24.Swap Nodes in Pairs
- 24. Swap Nodes in Pairs Leetcode 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
- **LeetCode 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs LeetCode
- 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
- [leetcode] 24. Swap Nodes in Pairs
- MFC解析URL
- DebugView输出调试信息
- css多排省略
- Android经验
- 欢迎使用CSDN-markdown编辑器
- 24. Swap Nodes in Pairs leetcode(list)
- iOS 10对隐私权限的管理(必须要改否则会crash)
- 单链表的逆置
- Android PopupWindow的使用和分析
- PHP输出PDF打印HTML5+CSS3打印格式控制
- 数据结构经典面试题——练习1
- vs2013下配置opencv2.4.9&openNI2提示错误:error LNK2019: 无法解析的外部符号
- Matlab与线性代数--矩阵的Cholesky分解
- EasyPR--一个开源的中文车牌识别系统