234. Palindrome Linked List
来源:互联网 发布:淘宝买q币交易关闭2017 编辑:程序博客网 时间:2024/06/08 04:28
Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?
s思路:
1. 套路题。先快慢指针找到中点,然后把后半部分reverse,然后两边都从头开始遍历,看是否相等。
class Solution {public: bool isPalindrome(ListNode* head) { // if(!head) return true; ListNode* fast=head->next,*slow=head; //step 1: 找中点 while(fast&&fast->next){ fast=fast->next->next; slow=slow->next; } //step 2:reverse the right half ListNode* pre=NULL,*pnow=slow->next,*pnext=NULL; slow->next=NULL; while(pnow){ pnext=pnow->next; pnow->next=pre; pre=pnow; if(!pnext) break; pnow=pnext; } //step 3:逐一比较 ListNode* l=head,*r=pnow; while(r){ if(r->val!=l->val) return false; r=r->next; l=l->next; } return true; }};
0 0
- 234. Palindrome Linked List
- 234. Palindrome Linked List
- 234. Palindrome Linked List
- 234. Palindrome Linked List
- 234. Palindrome Linked List
- 234. Palindrome Linked List
- 234. Palindrome Linked List
- 234. Palindrome Linked List
- 234. Palindrome Linked List
- 234. Palindrome Linked List
- 234. Palindrome Linked List
- 234. Palindrome Linked List
- 234. Palindrome Linked List
- 234. Palindrome Linked List
- 234. Palindrome (Linked List)
- 234. Palindrome Linked List
- 234. Palindrome Linked List
- 234. Palindrome Linked List
- Nginx遇上Access Denied提示怎么解决
- shell-03
- Java解析xml文件
- Android Studio系列教程四--Gradle基础
- CSS sticky footer
- 234. Palindrome Linked List
- 基于SqlServer+hibernate的简单分页查询
- centos7下安装mysql5.7.17
- 在method方法被调用之后,仅打印出a=100,b=200,请写出method方法的代码
- 【Ionic+AngularJS 开发】之『个人日常管理』App(一)
- 股票概述
- 快速实现基于FPGA的脉动FIR滤波器,VHDL,脉动阵列,PE处理单元,FIR滤波器
- java xml技术简单总结
- windows下mongodb设置用户名密码&用python连接