24. Swap Nodes in Pairs
来源:互联网 发布:java标识符是什么 编辑:程序博客网 时间:2024/06/08 16:30
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.
Subscribe to see which companies asked this question
题目要求每两个数之间交换一下。
感觉自己在链表这一块确实很薄弱,每次写都会遇到很多问题,真的是很不熟练。
自己这个题目思路不清晰,写的代码太凌乱了。
学习了别人的代码:http://blog.csdn.net/feliciafay/article/details/17573327
递归代码:
class Solution {public: ListNode* swapPairs(ListNode* head) { if(head==NULL||head->next==NULL) return head; ListNode *q=head->next; head->next=q->next; q->next=head; q->next->next=swapPairs(q->next->next); return q; }};
非递归的:
class Solution {public: ListNode* swapPairs(ListNode* head) { if(head==NULL||head->next==NULL) return head; ListNode *p=head; ListNode *q=head->next; ListNode *x=head->next->next; ListNode *t=NULL; head=q; while(p!=NULL&&q!=NULL){ p->next=NULL; q->next=p; if(t!=NULL) t->next=q; t=p; p=x; if(x!=NULL)q=x->next; if(q!=NULL)x=q->next; } if(p!=NULL) t->next=p; return head; }};
0 0
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24.Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- 24. Swap Nodes in Pairs
- LeetCode 003 Longest Substring Without Repeating Characters
- oracle异常处理
- HDU 4027 Can you answer these queries?(线段树、查询区间和及修改区间数为数的平方根)
- hibernate id 生成器
- CLOSE_WAIT状态的原因与解决方法
- 24. Swap Nodes in Pairs
- 用Jenkins搭建Android自动打包环境
- linux 解决大量SYN_RECV CLOSE_WAIT
- Parameters在Oozie的hive action中的使用
- 微信平台开发环境
- [ngix]CentOS6 下nginx的安装
- CLOSE_WAIT状态的讨论
- PGM - Week 1
- 搭建高可用MongoDB集群