File tree Expand file tree Collapse file tree 1 file changed +91
-0
lines changed
Love Babbar DSA Sheet Solutions/LinkedList Expand file tree Collapse file tree 1 file changed +91
-0
lines changed Original file line number Diff line number Diff line change 1+ // C++ program to implement
2+ // the above approach
3+ #include < bits/stdc++.h>
4+ using namespace std ;
5+
6+ class Node
7+ {
8+ public:
9+ int data;
10+ Node (int d)
11+ {
12+ data = d;
13+ }
14+ Node *ptr;
15+ };
16+
17+ // Function to check if the linked list
18+ // is palindrome or not
19+ bool isPalin (Node* head)
20+ {
21+ // Temp pointer
22+ Node* slow= head;
23+
24+ // Declare a stack
25+ stack <int > s;
26+
27+ // Push all elements of the list
28+ // to the stack
29+ while (slow != NULL )
30+ {
31+ s.push (slow->data );
32+
33+ // Move ahead
34+ slow = slow->ptr ;
35+ }
36+
37+ // Iterate in the list again and
38+ // check by popping from the stack
39+ while (head != NULL )
40+ {
41+ // Get the top most element
42+ int i=s.top ();
43+
44+ // Pop the element
45+ s.pop ();
46+
47+ // Check if data is not
48+ // same as popped element
49+ if (head -> data != i)
50+ {
51+ return false ;
52+ }
53+
54+ // Move ahead
55+ head=head->ptr ;
56+ }
57+ return true ;
58+ }
59+
60+ // Driver Code
61+ int main ()
62+ {
63+ // Addition of linked list
64+ Node one = Node (1 );
65+ Node two = Node (2 );
66+ Node three = Node (3 );
67+ Node four = Node (2 );
68+ Node five = Node (1 );
69+
70+ // Initialize the next pointer
71+ // of every current pointer
72+ five.ptr = NULL ;
73+ one.ptr = &two;
74+ two.ptr = &three;
75+ three.ptr = &four;
76+ four.ptr = &five;
77+ Node* temp = &one;
78+
79+
80+ // Call function to check
81+ // palindrome or not
82+ int result = isPalin (&one);
83+
84+ if (result == 1 )
85+ cout << " isPalindrome is true" ;
86+ else
87+ cout << " isPalindrome is true" ;
88+
89+ return 0 ;
90+ }
91+ // This code has been contributed by Striver
You can’t perform that action at this time.
0 commit comments