LeetCode 234. Palindrome Linked List
2016-03-09 01:03
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?
一,算法分析
大体思想是利用快慢两个指针找到中间节点,然后将后面半个链表进行逆转;依次与前半部分比较,若相等则说明是回文串;
二,C语言实现
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode *reverseList(struct ListNode *head){
struct ListNode *p,*q;
p=head->next;
head->next=NULL;
while(p!=NULL){
q=p->next;
p->next=head;
head=p;
p=q;
}
return head;
}
bool isPalindrome(struct ListNode* head) {
struct ListNode *fast,*slow,*middle;
if(head==NULL || head->next==NULL)
return true;
fast=head;
slow=head;
while(fast->next!=NULL && fast->next->next!=NULL){
slow=slow->next;
fast=fast->next->next;
}
middle = reverseList(slow->next);
slow->next=NULL;//这个非常关键,否则下面的while循环死掉了
while(middle!=NULL && head!=NULL){//这里应该是判断两个,有一个为NULL就停止
if(head->val!=middle->val)
return false;
head=head->next;
middle=middle->next;
}
return true;
}
重要的是一些边界问题的确认,与循环截止条件的设置。
Follow up:
Could you do it in O(n) time and O(1) space?
一,算法分析
大体思想是利用快慢两个指针找到中间节点,然后将后面半个链表进行逆转;依次与前半部分比较,若相等则说明是回文串;
二,C语言实现
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode *reverseList(struct ListNode *head){
struct ListNode *p,*q;
p=head->next;
head->next=NULL;
while(p!=NULL){
q=p->next;
p->next=head;
head=p;
p=q;
}
return head;
}
bool isPalindrome(struct ListNode* head) {
struct ListNode *fast,*slow,*middle;
if(head==NULL || head->next==NULL)
return true;
fast=head;
slow=head;
while(fast->next!=NULL && fast->next->next!=NULL){
slow=slow->next;
fast=fast->next->next;
}
middle = reverseList(slow->next);
slow->next=NULL;//这个非常关键,否则下面的while循环死掉了
while(middle!=NULL && head!=NULL){//这里应该是判断两个,有一个为NULL就停止
if(head->val!=middle->val)
return false;
head=head->next;
middle=middle->next;
}
return true;
}
重要的是一些边界问题的确认,与循环截止条件的设置。
相关文章推荐
- 如何组织构建多文件 C 语言程序(二)
- [C/C++]反转链表
- 如何写好 C main 函数
- 书评:《算法之美( Algorithms to Live By )》
- 动易2006序列号破解算法公布
- C#实现基于链表的内存记事本实例
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- Lua和C语言的交互详解
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析
- 关于C语言中参数的传值问题
- 简要对比C语言中三个用于退出进程的函数
- 深入C++中API的问题详解
- 基于C语言string函数的详解
- C语言中fchdir()函数和rewinddir()函数的使用详解