-
Notifications
You must be signed in to change notification settings - Fork 34
/
24.cpp
77 lines (66 loc) · 1.64 KB
/
24.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
// Program to check if a given linked list of strings
// form a palindrome
#include <bits/stdc++.h>
using namespace std;
/* Link list node */
struct Node
{
string data;
Node* next;
};
// A utility function to check if str is palindrome
// or not
bool isPalindromeUtil(string str)
{
int length = str.length();
// Match characters from beginning and
// end.
for (int i=0; i<length/2; i++)
if (str[i] != str[length-i-1])
return false;
return true;
}
// Returns true if string formed by linked
// list is palindrome
bool isPalindrome(Node *node)
{
// Append all nodes to form a string
string str = "";
while (node != NULL)
{
str.append(node->data);
node = node->next;
}
// Check if the formed string is palindrome
return isPalindromeUtil(str);
}
// A utility function to print a given linked list
void printList(Node *node)
{
while (node != NULL)
{
cout << node->data << " -> ";
node = node->next;
}
printf("NULL\n");
}
/* Function to create a new node with given data */
Node *newNode(const char *str)
{
Node *new_node = new Node;
new_node->data = str;
new_node->next = NULL;
return new_node;
}
/* Driver program to test above function*/
int main()
{
Node *head = newNode("a");
head->next = newNode("bc");
head->next->next = newNode("d");
head->next->next->next = newNode("dcb");
head->next->next->next->next = newNode("a");
isPalindrome(head)? printf("true\n"):
printf("false\n");
return 0;
}