LeetCode 234 Palindrome Linked List
2016-04-08 01:12
393 查看
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?
思路:把链表分为前后两半部分,把后半部分链表进行反转,然后一起遍历前后两半部分链表,依次比较节点的值。
Follow up:
Could you do it in O(n) time and O(1) space?
思路:把链表分为前后两半部分,把后半部分链表进行反转,然后一起遍历前后两半部分链表,依次比较节点的值。
public boolean isPalindrome(ListNode head) { if (head == null || head.next == null) return true; ListNode fast = head, slow = head;//利用快慢指针,寻找中间节点 while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } /*** Start:对链表后半部分进行反转 By yuanyuan.niu*/ ListNode pre = slow, cursor = slow.next; while (cursor != null) { ListNode tmp = cursor.next; cursor.next = pre; pre = cursor; cursor = tmp; } slow.next = null; /**end反转链表结束,pre作为链表后半部分反转后的头节点*/ while (pre != null) { if (head.val != pre.val) return false; pre = pre.next; head = head.next; } return true; }
相关文章推荐
- Textarea根据内容自适应高度
- 查看python的安装目录
- js内存泄漏
- 计算器稍微小结
- 浏览器支持&兼容性查询(CSS、Html5、SVG、JS-Api)
- (Cuda)流Stream(三)
- php实习tips(mysql_query的结果返回值与判断)
- ArchLinux 扬声器和麦克风不能使用的问题
- 2005年上海交通大学计算机研究生机试真题
- textarea文本域自适应高度
- BZOJ4504 : K个串
- Runtime的使用
- jquery实现textarea 高度自适应
- 用Redis轻松实现秒杀系统
- java 处理系统时间(转载)
- 吴超老师课程--Hive的执行语句
- jquery ajax无刷新更新页面
- div模拟textarea文本域轻松实现高度自适应
- “SQLServerAgent当前未运行”问题解决
- php的tips(数组排序函数)