算法第五周Swap Nodes in Pairs[medium]
来源:互联网 发布:java怎么读inputstream 编辑:程序博客网 时间:2024/04/30 18:31
Swap Nodes in Pairs[medium]
Description
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.
Analysis
题目是很容易理解的。就是将相邻的结点交换,并且题目中明确要求不能直接交换结点的值,同时,从题目中我们能够看出他是每两个结点进行一次交换。我采用的方法是每三个结点交换后两个,首先创建一个结点h,它的next指针指向list的head,如果h的下一个和下下个均不为空,我们即可利用h来交换后两个结点,之后更新h的值,是他等于上一次处理的最后一个结点。
Solution
/** * 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* h = new ListNode(1); h->next = head; ListNode* c = h; ListNode* p = NULL; ListNode* t = NULL; while (c->next != NULL &&c->next->next != NULL) { p = c->next; t = c->next->next; p->next = t->next; c->next = t; t->next = p; c = p; } return h->next; }};
阅读全文
0 0
- 算法第五周Swap Nodes in Pairs[medium]
- (算法分析Week11)Swap Nodes in Pairs[Medium]
- [Leetcode 24, Medium] Swap Nodes in Pairs
- 算法 Swap Nodes in Pairs
- 算法设计与分析(17)-- Swap Nodes in Pairs(难度:Medium)
- [LeetCode] 024. Swap Nodes in Pairs (Medium) (C++/Python)
- LeetCode-24-Swap Nodes in Pairs(链表)-Medium
- LeetCode刷题——Swap Nodes in Pairs(Medium)
- Leetcode OJ 24 Swap Nodes in Pairs [Medium]
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes In Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Swap Nodes in Pairs
- Unity_版本切换_预编译手段
- 2017/10/7
- 零基础入门深度学习(3)
- 笔记-感知机、超平面
- Mysql——关系数据库之笛卡尔积
- 算法第五周Swap Nodes in Pairs[medium]
- Qt数据库操作报错not positioned on a valid record
- Rust: trim(),trim_matches()等江南六怪......
- 零基础入门深度学习(4)
- Construct 2作業
- 《一个操作系统的实现》笔记(1)--NASM汇编语法和环境搭建
- 在 PyCharm 2017.2.3 中设置 Anaconda 5.0.0 中配置的多Python环境
- 如何在CentOS 6上安装Python 2.7 + Ansible
- MyBatis中常见的几种错误解决方法