[Leetcode 234, Easy] Palindrome Linked List
2015-07-19 04:59
447 查看
Problem:
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?
Analysis:
Solutions:
C++:
Python:
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?
Analysis:
Solutions:
C++:
bool isPalindrome(ListNode* head) { if(head == NULL || head->next == NULL) return true; if(head->next->next == NULL) return (head->val == head->next->val ? true : false); ListNode *fast = head; ListNode *slow = head; while(fast->next != NULL && fast->next->next != NULL) { slow = slow->next; fast = fast->next; fast = fast->next; } ListNode *new_head = NULL; ListNode *new_cur = NULL; ListNode *p_cur = head; ListNode *p_temp = slow->next; bool till_last_node(fast->next == NULL); while(p_cur->next != NULL) { ListNode *temp_next = p_cur->next; if(new_cur == NULL) { new_head = p_cur; new_cur = p_cur; new_head->next = NULL; } else { new_head = p_cur; new_head->next = new_cur; new_cur = new_head; } p_cur = temp_next; if(till_last_node) { if(p_cur == slow) { p_cur = p_cur->next; break; } } else { if(p_cur == p_temp) break; } } while(p_cur != NULL) { if(p_cur->val != new_cur->val) return false; p_cur = p_cur->next; new_cur = new_cur->next; } return true; }Java:
Python:
相关文章推荐
- CentOS7 安装NFS SSH免密码登陆
- 反编译apk
- 文件类功能 与 排序类功能 汇总总结
- PRPDebug
- 实践证明一个醒目的标题可以促进百度蜘蛛的喜好达到收录的目的
- 创建你的第一个JavaScript库
- csdn图片管理
- arcsde 0xc0000007b
- CentOS7 安装LNMP(Linux+Nginx+MySQL+PHP)
- mariadb galera集群配置
- Codeforces Gym 100187K K. Perpetuum Mobile 构造
- 交换两个变量,不使用第三个变量(js向)
- 面向对象之抽象和接口
- 面向对象之多态
- 面向对象之继承
- 面向对象之封装
- openssl构建CA认证
- ntop监控系统网络状态-安装配置
- Linux与Unix shell编程指南(完整高清版).pdf
- 求Sn=1!+2!+3!+4!+5!+…+n!之值,其中n是一个数字