-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpalindromeLL.cpp
132 lines (121 loc) · 2.82 KB
/
palindromeLL.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
/* Program to check if a linked list is palindrome */
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
void printList(struct Node *ptr);
/* Link list node */
struct Node
{
char data;
struct Node* next;
};
static void reverse(struct Node** head_ref)
{
if(*head_ref == NULL)
printf("list is empty");
struct Node *prev = NULL;
struct Node *current = *head_ref;
struct Node *next;
while(current != NULL)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*head_ref = prev;
}
/* Function to check if two input lists have same data*/
bool compareLists(struct Node* head1, struct Node *head2)
{
while(head1 != NULL && head2 != NULL)
{
if (head1->data == head2->data)
{
head1 = head1->next;
head2 = head2->next;
}
else
return false;
}
if(head1 == NULL && head2 == NULL)
return true;
return false;
}
/* Function to check if given linked list is
palindrome or not */
bool isPalindrome(struct Node *head)
{
if(head == NULL || head->next == NULL)
return true;
struct Node *spt = head;
struct Node *fpt = head;
struct Node *midnode = NULL;
struct Node *secondhalf = NULL;
struct Node *prevofspt = head;
while(fpt != NULL && fpt->next != NULL)
{
prevofspt = spt;
spt = spt->next;
fpt = fpt->next->next;
}
if(fpt != NULL)
{
midnode = spt;
spt = spt->next;
}
secondhalf = spt;
prevofspt->next = NULL;
reverse(&secondhalf);
bool res = compareLists(head,secondhalf);
reverse(&secondhalf);
if(midnode != NULL)
{
prevofspt->next = midnode;
midnode->next = secondhalf;
}
else
{
prevofspt->next = secondhalf;
}
return res;
}
void push(struct Node** head_ref, char new_data)
{
/* allocate node */
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to pochar to the new node */
(*head_ref) = new_node;
}
// A utility function to print a given linked list
void printList(struct Node *ptr)
{
while (ptr != NULL)
{
printf("%c->", ptr->data);
ptr = ptr->next;
}
printf("NULL\n");
}
/* Drier program to test above function*/
int main()
{
/* Start with the empty list */
struct Node* head = NULL;
char str[] = "abacaba";
//char str[] = "aba";
int i;
for (i = 0; str[i] != '\0'; i++)
{
push(&head, str[i]);
printList(head);
isPalindrome(head)? printf("Is Palindrome\n\n"):
printf("Not Palindrome\n\n");
}
return 0;
}