Leetcode-234. Palindrome Linked List(判断链表是否回文)
2016-06-03 10:43
471 查看
要求使用O(n)的时间复杂度和O(1)的空间复杂度
这里使用fast指针每次走两步,slow每次走一步。aux逆序记录slow走过的节点。
当fast走到终点,slow走过一半,再把链表slow和aux做比较。
其中有一点要注意slow=slow->next必须在temp->next=aux之前,具体原因可画图理解。
class Solution { public: bool isPalindrome(ListNode* head) { ListNode *fast=head,*slow=head,*aux=NULL,*temp; while(fast&&fast->next){ temp=slow; fast=fast->next->next; slow=slow->next; temp->next=aux; aux=temp; } if(fast) {slow=slow->next;} while(slow){ if(aux->val!=slow->val) return false; slow=slow->next; aux=aux->next; } return true; } };
这里使用fast指针每次走两步,slow每次走一步。aux逆序记录slow走过的节点。
当fast走到终点,slow走过一半,再把链表slow和aux做比较。
其中有一点要注意slow=slow->next必须在temp->next=aux之前,具体原因可画图理解。
相关文章推荐
- Android动画机制与使用技巧(四)——Android动画特效
- linux系统c线程池的实现
- shell 脚本之for
- 求一组整数的第k小的数
- 强悍的 ubuntu —— ubuntu 下的文件搜索
- CAS-ERR Cannot create a session after the response has been committed
- KeilC51使用详解 (一)
- 解决Asp.net Mvc返回JsonResult中DateTime类型数据格式问题的方法
- 237. Delete Node in a Linked List
- AFN3.0API调用
- smartUpload组件的简单总结
- iOS多线程学习笔记
- 库函数方式文件编程----fopen
- 论项目采购管理
- URL与 HTTP,iOS中发送HTTP请求
- IOS视图控制器左边缘右滑pop出栈
- iOS开发过程中字体的大小,加粗等问题的显示
- 信用卡安全问题
- 贝叶斯经典文献!
- JSON字符串转换JSONObject和JSONArray的方法