234. Palindrome Linked List
来源:互联网 发布:php如何解决高并发问题 编辑:程序博客网 时间:2024/06/10 23:45
问题:
234. Palindrome Linked List(从前往后读和从后往前读是一样的)
参考链接:
1、【LeetCode】234. Palindrome Linked List (2 solutions)
2、http://www.cnblogs.com/HorribleMe/p/4878833.html
第一种解法:
(符合题目要求:时间复杂度O(n),空间复杂度O(1))
思想:
找到链表中点,拆分后,逆转后半个链表,然后两个链表同时顺序遍历一次。
图解:
代码:
/** * 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 *mid=getmid(head);//中间节点 ListNode *head2=rever(mid);//中间节点作为头指针的链表反转 while(head&&head2) { if(head->val!=head2->val) return false; else head=head->next; head2=head2->next; } return true; }private: ListNode* getmid(ListNode *head) { ListNode *slow=head; ListNode *fast=head; if (!head||!head->next) return head; while(fast) { slow=slow->next; fast=fast->next; if (fast) fast=fast->next; } return slow; }private: ListNode* rever(ListNode *head) { ListNode *prev = NULL, *cur = head, *tmp; while(cur) { tmp=cur->next; cur->next=prev; prev=cur; cur=tmp; } return prev; }};
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
- ios 毛玻璃设置
- 对一个栈进行排序
- Centos7上安装PHP-Redis扩展以及一些简单的实用
- 红黑树——java实现
- MFC中设置socket超时
- 234. Palindrome Linked List
- synchronized同步方法
- Windows 平台安装 MongoDB
- 【译】Performance tips when writing shaders
- SeekBar
- Ubuntu上安装和使用Android Studio
- 51nod_1057 N的阶乘(大数)
- Java Spring mvc 操作 Redis 及 Redis 集群
- 设计模式C++原型模式