-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathisListPalindrome.h
72 lines (68 loc) · 1.69 KB
/
isListPalindrome.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
//
// Created by so_go on 2019/6/6.
//
#ifndef SRC_ISLISTPALINDROME_H
#define SRC_ISLISTPALINDROME_H
#include<iostream>
using namespace std;
// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
void printList(ListNode *head){
ListNode *cur = head;
while(cur){
cout << cur->val << ' ';
cur = cur->next;
}
cout << endl;
}
class IsListPalindrome {
public:
bool isPalindrome(ListNode* head) {
ListNode *cur = head;
int count = 0;
while(cur){
cur = cur->next;
count++;
}
cout << count << endl;
int half = count / 2;
// 将前半部分原地逆置。
// 对于当前节点,保存下一个节点,将当前节点插入链表头部
ListNode *rhead = NULL, *next;
cur = head;
for(int i = 0; i < half; i++){
next = cur->next;
cur->next = rhead;
rhead = cur;
cur = next;
}
printList(rhead);
printList(cur);
ListNode *rptr = rhead;
if( count % 2 == 0){
for(int i = 0; i < half; i++){
if( rptr->val != cur->val){
return false;
}
rptr = rptr->next;
cur = cur->next;
}
}
else{
cur = cur->next;
for(int i = 0; i < half; i++){
if(rptr->val != cur->val){
return false;
}
rptr = rptr->next;
cur = cur->next;
}
}
return true;
}
};
#endif //SRC_ISLISTPALINDROME_H