LeetCode--Swap Nodes in Pairs
来源:互联网 发布:知乎 未解之谜 编辑:程序博客网 时间:2024/06/01 11:18
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.
方法一:递归法。每次交换前两个,并递归调用交换后面的,交换后面的时候也是先交换前两个,直到不能交换。
/** * 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* newhead=head->next; head->next=swapPairs(newhead->next); newhead->next=head; return newhead; }};
方法二:定义一个辅助的头结点和头指针(会发现很方便)。直接正向思维,交换每相邻的两个节点,记录第三个节点更新给当前的头指针的下一个即可,这里的头指针每次都是更新为待交换两个节点前的那个。
/** * 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 dummy(0); ListNode *cur=&dummy; while(head&&head->next){ ListNode *next=head->next->next; cur->next=head->next; cur=cur->next; cur->next=head; cur=cur->next; head->next=NULL; head=next; } if(head) cur->next=head; return dummy.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
- 使用VIM搜索多个文件
- Eclipse+ADT+Android SDK 搭建安卓开发环境
- mongoDB服务器的安装配置
- 安卓 ExpandableListView的使用详解
- nginx windows 配置
- LeetCode--Swap Nodes in Pairs
- Kali->arp欺骗
- phpMyAdmin访问被拒绝!
- 考题http://blog.csdn.net/xllily_11/article/details/70899191
- Android之RSA校验
- iscroll实现下拉刷新,上拉加载
- mac自带本地web服务器的使用
- Window10安装VS2013 中文语言包提示程序兼容性已打开,请将其关闭
- 基于线性表的查找法