【Leetcode】Palindrome Linked List
2015-11-19 22:31
281 查看
题目链接:https://leetcode.com/problems/palindrome-linked-list/
题目:
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?
思路:
1、用栈存储然后比较,无需改动链表结构,不过空间复杂度为O(n)
2、修改链表结构。找到中间结点,反转中间结点一边链表,然后中间结点两边链表比较。
算法1:
算法2:
题目:
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?
思路:
1、用栈存储然后比较,无需改动链表结构,不过空间复杂度为O(n)
2、修改链表结构。找到中间结点,反转中间结点一边链表,然后中间结点两边链表比较。
算法1:
public boolean isPalindrome(ListNode head) { Stack<Integer> stack = new Stack<Integer>(); ListNode p = head; while (p != null) { stack.push(p.val); p = p.next; } p = head; while (p != null) { int tmp = stack.pop(); if (tmp != p.val) { return false; } p = p.next; } return true; }
算法2:
public int getListLength(ListNode head) { int length = 0; ListNode p = head; while (p != null) { length++; p = p.next; } return length; } public ListNode reverseList(ListNode head) { ListNode p = head, q, t; if (p == null) return head; q = p.next; while (q != null) { t = q.next;// 保存当前要处理结点后面的一个结点 q.next = p; p = q; // p是新链表头结点 q = t; } head.next = null;// 原头结点变成尾节点 head = p; return head; } public boolean isPalindrome(ListNode head) { if (head == null || head.next == null) { return true; } int length = getListLength(head); int i = length / 2; ListNode p = head, l2 = null; while (--i > 0) p = p.next; if (length % 2 == 0) { l2 = p.next; } else { l2 = p.next.next; } p.next = null; l2 = reverseList(l2); while (head != null) { if (head.val != l2.val) { return false; } else { head = head.next; l2 = l2.next; } } return true; }
相关文章推荐
- AndroidStudio中方法注释模板快捷键的设置
- Android四大组件之Service
- Python __getattr__与__setattr__使用方法
- 第一个Web前端
- iOS页面间传值的方式(Delegate/NSNotification/Block/NSUserDefault/单例)
- Group Anagrams
- PAT-PAT (Advanced Level) Practise To Buy or Not to Buy(20) 【一星级】
- EventBroker
- Xcode7.0后,如何配置Pch
- 13.按比例显示图片、自定义属性、测量
- 百度api定位
- gradle eclipse下构建ssh2项目
- ofbiz框架以及核心原理介绍
- bzoj-2555 SubString
- 从头认识java-9.10 Map
- 网页设计大赛第三天
- 制造大数据表
- LeetCode第一题Two Sum
- matlab连接MySQL
- MATLAB与数据库Mysql的链接