【C++】【LeetCode】24. Swap Nodes in Pairs
来源:互联网 发布:淘宝怎么交电费 编辑:程序博客网 时间:2024/06/04 18:46
题目
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.
思路
如果给定的链表为空,或者只有1个结点,则直接返回链表。
如果给定的链表大于等于2个结点,则交换两个结点,然后继续往下判断接下来两个结点是否为NULL。
注意:使用 && 时,当前者不满足条件,不执行后者,不会发生NULL->next,所以不会出错。
代码
/** * 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) { ListNode *tmpPre; if (head == NULL) { return head; } else if (head->next == NULL) { return head; } else { ListNode *tmp = head; head = head->next; tmp->next = head->next; head->next = tmp; tmpPre = head->next; } while (tmpPre->next != NULL && tmpPre->next->next != NULL) { ListNode *tmp = tmpPre->next; tmpPre->next = tmpPre->next->next; tmp->next = tmpPre->next->next; tmpPre->next->next = tmp; tmpPre = tmpPre->next->next; } return head; }};
阅读全文
0 0
- 【C++】【LeetCode】24. Swap Nodes in Pairs
- leetcode: Swap Nodes in Pairs (C++)
- 【LeetCode-24】Swap Nodes in Pairs(C++)
- Leetcode c语言-Swap Nodes in Pairs
- 【LeetCode】24. Swap Nodes in Pairs C语言
- [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
- 练手Demo——原生javaScript写日历
- 第三方登陆及社会化分享
- vs2010中各类文件的作用
- 安卓反编译入门详解
- 将网站打造成单页面应用SPA
- 【C++】【LeetCode】24. Swap Nodes in Pairs
- Eclipse Memory Analyzer tool(MAT)分析内存泄露(一)
- 机器学习——决策树 知识点总结
- C语言中的内存问题(51单片机应用中出现的问题)
- 线性表——链式存储结构之单链表
- java面试题持续更新
- oracle 删除用户时" 表或视图不存在"的问题
- ML算法(常见机器学习算法公式)
- Struts2类型转换器