234. Palindrome Linked List
2016-03-24 21:58
295 查看
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?
题意:判断一个单链表是否回文。
思路:先确定链表的长度,然后将链表右半段反转,进行值对比,在把右半段反转回来。
<span style="font-size:14px;">/** * 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) { int count = 0; ListNode* p = head; while (p){ count++; p = p->next; } if (count <= 1) return true; p = head; for (int i = 0; i < count/2 -1; i++) p = p->next; ListNode* q = NULL; if ((count & 1) == 1){ q = p->next->next; } else{ q = p->next; } q = reverseList(q); p = head; while (p && q){ if (p->val == q->val){ p = p->next; q = q->next; } else{ return false; } } reverseList(q); return true; } ListNode* reverseList(ListNode* head) {//链表反转算法,在206. Reverse Linked List if (head == NULL) return head; ListNode *p, *q, *r; p = NULL; q = head; r = head->next; while (r){ q->next = p; p = q; q = r; r = r->next; } q->next = p; return q; } };</span>
相关文章推荐
- “耐撕”团队 2016.03.24 站立会议
- 细说各种经典端口
- 上机作业2-2
- Office word图表目录多个标题之间的空行无法删除
- redis中的事务
- mcrypt pdo_mysql 等同类安装
- 世界是数字的
- 《世界是数字的》 读后感
- Learning Python-the third chapter
- 初识Spring
- iOS开发中代码块的使用
- Android存储数据到sdcard
- 卿学姐种花(线段树)
- jQuery mobile开发之页面(链接)跳转刷新问题
- ps aux 命令分析
- Android AsynTask
- UTF-8中的BOM
- Binary Search(二分)
- redis hash结构及命令详解
- Hive日志分析案例二