-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathpalindromelinkedlist.cpp
93 lines (87 loc) · 1.76 KB
/
palindromelinkedlist.cpp
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# include <iostream>
using namespace std;
struct Node
{
int v;
Node *next;
};
void printlinkedlist(Node *root)
{
Node *p=root;
if(p==NULL)
return;
while(p!=NULL)
{
cout<<p->v<<" ";
p=p->next;
}
cout<<endl;
return;
}
Node *rev(Node *root)
{
Node *p=root;
Node *parent=NULL;
if(p==NULL)
return NULL;
while(p!=NULL)
{
//cout<<p->v<<" ";
//At a pointer p: Have the parent pointer set it to be the next pointer
Node *temp=p->next;
p->next=parent;
parent=p;
p=temp;
}
//parent contains the last node
Node *start=parent;
return start;
}
bool palindromelinkedlist(Node *n1,Node *n2)
{
bool ret;
while(n1!=NULL)
{
if(n1->v!=n2->v)
return false;
n1=n1->next;
n2=n2->next;
}
return true;
}
int main()
{
Node *test=new(Node);
test->v=3;
test->next=new(Node);
test->next->v=6;
test->next->next=new(Node);
test->next->next->v=8;
test->next->next->next=new(Node);
test->next->next->next->v=10;
test->next->next->next->next=NULL;
Node *test2=new(Node);
test2->v=3;
test2->next=new(Node);
test2->next->v=6;
test2->next->next=new(Node);
test2->next->next->v=6;
test2->next->next->next=new(Node);
test2->next->next->next->v=3;
test2->next->next->next->next=NULL;
printlinkedlist(test);
Node *ret=rev(test);
printlinkedlist(ret);
if(palindromelinkedlist(test,ret))
cout<<"PALINDROME";
else
cout<<"NOT PALINDROME";
cout<<endl;
printlinkedlist(test2);
Node *ret2=rev(test2);
printlinkedlist(ret2);
if(palindromelinkedlist(test2,ret2))
cout<<"PALINDROME";
else
cout<<"NOT PALINDROME";
}