leetcode 234. Palindrome Linked List
来源:互联网 发布:mysql utf8 utf8mb4 编辑:程序博客网 时间:2024/06/18 07:40
原题:
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?
主要的难点在于时间和空间的要求
代码如下:
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */bool isPalindrome(struct ListNode* head) { struct ListNode* fast; struct ListNode* slow; fast=head; slow=head; if(head==NULL||head->next==NULL) return true; while(fast&&fast->next) { slow=slow->next; fast=fast->next->next; } struct ListNode* otherhead; otherhead=(struct ListNode*)malloc(sizeof(struct ListNode)); otherhead->next=NULL; struct ListNode* p1; struct ListNode* p2; if(!fast) { p1=slow; } else { p1=slow->next; } while(p1) { p2=otherhead->next; otherhead->next=p1; p1=p1->next; otherhead->next->next=p2; } while(otherhead->next) { if(otherhead->next->val!=head->val) { return false; } otherhead=otherhead->next; head=head->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
- 开发过程遇到的IE兼容性问题以及解决方案
- 【Python爬虫系列】使用requests爬取图片
- 使用反射机制调用属性和私有成员与代理模式的介绍
- numpy中arange和reshape的用法
- C++ 删除文件夹
- leetcode 234. Palindrome Linked List
- gpstop failed. (Reason='int() argument must be a string or a number, not 'NoneType'') exiting...
- 各种数据库的jdbc驱动下载及连接方式
- linux基础命令学习笔记~1
- 一个线程的独白
- FatMouse's trade
- JavaScript中的作用域和作用域链
- 亚马逊架构师:私有云计算有没有前途
- 判断一个二叉树是否是AVL树