【leetcode每日一题】24.Swap Nodes in Pairs
来源:互联网 发布:上海知恩服饰有限公司 编辑:程序博客网 时间:2024/05/01 20:04
题目:
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.
解析:定义三个节点temp、first和second,temp指向上一节点,first指向当前节点,second指向下一节点。让temp指向second,first指向second的下一节点,second指向first。然后依次遍历整个链表即可。代码如下:
/** * 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) return head; ListNode *first=head; ListNode *second=first->next; ListNode *temp=first; head=second; while(first!=NULL&&second!=NULL) { temp->next=second; first->next=second->next; second->next=first; temp=first; first=first->next; if(first!=NULL) second=first->next; } return head; }};
0 0
- 【leetcode每日一题】24.Swap Nodes in Pairs
- [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
- LeetCode 24. Swap Nodes in Pairs
- LeetCode-24.Swap Nodes in Pairs
- 问题
- OC中如何进行多文件开发?
- iOS——创建Xcode 的Hello World
- 做葡萄酒全过程
- Linux/ubuntu 截图工具的使用
- 【leetcode每日一题】24.Swap Nodes in Pairs
- 本人是一名专科学生,现自学java,记录学习。希望能够大家多多提提意见
- 伪分布式hadoop环境搭建
- Leetcode #260 Single Number III
- 黑马程序员---------Java基础------------多线程简单总结
- T-SQL 公用表表达式(CTE)
- Calendar实现得到指定月的第一天和最后一天
- 多态
- 错误纪录1