【LeetCode】Swap Nodes in Pairs
来源:互联网 发布:家用手动工具套装 知乎 编辑:程序博客网 时间:2024/05/05 23:20
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.
分析:每次读两个节点插入新链表,因为是指针操作,不占用额外空间。最后需要把tail指针的next设为NULL。例如链表为p1->p2->p3->p4的情况,如果最后不修改p3->next,那么就会出现一个环:p2->p1->p4->p3->p4->...
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ // 时间复杂度 O(n),空间复杂度 O(1)class Solution {public: ListNode *swapPairs(ListNode *head) { if(nullptr==head || nullptr==head->next) return head; ListNode init(-1); init.next = head; for(ListNode *prev=&init,*cur=prev->next,*next=cur->next; next; prev=cur,cur=cur->next,next=cur?cur->next:nullptr){ prev->next = next; //把头指针设置为要交换第二个数 cur->next = next->next;// 把要交换的第一个数的next设置为第二个数的next next->next = cur; // 把要交换的第二个数的next设置为第一个数 } return init.next; }};
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
- JUnit使用OpenSessionInView
- 如何在CentOS6.5中配置windows用户登录VNC服务器
- ORACLE 11G 64位 桌面类 WIN7 安装
- 解决Android中TranslateAnimation后出现残影的问题
- 十五分钟介绍 Redis数据结构
- 【LeetCode】Swap Nodes in Pairs
- 计算机书单(刘未鹏)
- Windows7上搭建cocos2d-x-3.2 Android开发环境
- 一道只能用乘法不能用除法的数组面试题
- IOS 以任意点为圆心 旋转UIView
- LeetCode 142 Regular Expression Matching
- Codeforces Round #265 (Div. 2) C - No to Palindromes!
- 三大WEB服务器对比分析(apache ,lighttpd,nginx)
- C语言指针转换为intptr_t类型