[leetcode] 234. Palindrome Linked List
来源:互联网 发布:silence网络什么意思 编辑:程序博客网 时间:2024/06/05 05:56
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?
解法一:
核心是分别有快慢两个指针,去获取list的中心node的坐标。同时使用一个stack,存储前半段node的数值。这里有一个地方要注意,当list长度是奇数时,slow正好停在正中心。当list长度是偶数时,需要将slow的当前值再push一次。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: bool isPalindrome(ListNode* head) { if (!head || !head->next) return true; ListNode* slow = head, *fast = head; stack<int> vals; while(fast->next && fast->next->next){ vals.push(slow->val); slow = slow->next; fast = fast->next->next; } if (fast->next) vals.push(slow->val); while(slow->next){ if (slow->next->val!=vals.top()) return false; else{ slow = slow->next; vals.pop(); } } return true; }};
解法二:
获得list中心还是一样,然后需要翻转后半段list。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: bool isPalindrome(ListNode* head) { if (!head || !head->next) return true; ListNode* slow = head, *fast = head; while(fast->next && fast->next->next){ slow = slow->next; fast = fast->next->next; } ListNode* cur = slow->next; while(cur->next){ ListNode* tmp = cur->next; cur->next = tmp->next; tmp->next = slow->next; slow->next = tmp; } slow = slow->next; while(head && slow){ if (head->val != slow->val) return false; head = head->next; slow = slow->next; } return true; }};
0 0
- [leetcode] 234.Palindrome Linked List
- [LeetCode]234.Palindrome Linked List
- [leetcode] 234.Palindrome Linked List
- 【leetcode】234. Palindrome Linked List
- 【LeetCode】234. Palindrome Linked List
- [leetcode] 234. Palindrome Linked List
- 234. Palindrome Linked List LeetCode
- LeetCode--234. Palindrome Linked List
- LeetCode 234. Palindrome Linked List
- 【LeetCode】234. Palindrome Linked List
- leetcode 234. Palindrome Linked List
- LeetCode *** 234. Palindrome Linked List
- LeetCode 234. Palindrome Linked List
- leetcode-234. Palindrome Linked List
- LeetCode-234.Palindrome Linked List
- 【LeetCode】234. Palindrome Linked List
- [Leetcode]234. Palindrome Linked List
- 【leetcode】234. Palindrome Linked List
- Java递归
- SDUT 递归的函数 2176
- Python学习笔记--2016.07.28
- 敏捷健康指南
- HTMl5的sessionStorage和localStorage
- [leetcode] 234. Palindrome Linked List
- centos git更新、搭建git服务器
- 报错:07-28 11:02:19.121: E/AndroidRuntime(5867): Caused by: java.lang.ArrayIndexOutOfBoundsException:
- 题目171 聪明的kk
- 树莓派3 读取DS18B20 温度
- android设置在ListView中让TextView滚动
- Unity3D Shader官方教程翻译(三)----Shader语法:属性
- ffmpeg-格式获取
- Linux--su和sudo用法