234. Palindrome Linked List。
来源:互联网 发布:mac outlook windows 编辑:程序博客网 时间:2024/06/14 15:06
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?
判断这个链表是不是回文,我的思路就是先找到链表的中间值,在找的过程中将前半段的数据放在栈中,然后找到中间之后,在分别从栈中出栈,然后和后半部分进行比较,如果中间出现不相等的数据就返回false,否则到最后返回true即可。
#include <iostream>#include <stack>using namespace std;struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {}};class Solution {public: bool isPalindrome(ListNode* head) { stack<int> halfValues;//使用一个栈来保存链表前半边的节点. ListNode* fast = head; ListNode* slow = head; if(!head) { return true; } while(fast&&fast->next) {//使用快慢指针找到链表中点 fast = fast->next->next; halfValues.push(slow->val); slow = slow->next; } if(fast) {//fast指向不为空说明为奇数,此时不需要比较最中间的那个数值 slow = slow->next; } while(slow) {//不为空则遍历 if(slow->val != halfValues.top()) { return false; } else { halfValues.pop(); slow = slow->next; } } return true; }};int main() { Solution s; ListNode node1(1); ListNode node2(2); ListNode node3(2); ListNode node4(1); node1.next = &node2; node2.next = &node3; node3.next = &node4; cout << s.isPalindrome(&node1);}
阅读全文
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
- day10-jQuery进阶语法
- poj 2398 Toy Storage
- Node fs.writeFileSync 操作中 UTF-8 格式 BOM 缺失
- 浅谈排序
- == equals compareTo 区别
- 234. Palindrome Linked List。
- html5的本地存储
- 初探spring boot
- 双向链表的奇偶节点交换(即1节点和2节点交换,然后3节点和4节点交换)
- python---语句与数据结构应用,迭代、迭代字典、字典排序、字典根据键值查找键、sorted排序方法、translate与maketrans、with语句
- Genymotion启动不了
- qt正则表达式类QRegExp
- java全排列
- Netty介绍(附视频教程)