-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpalindrome_linked_list.cpp
More file actions
65 lines (61 loc) · 1.48 KB
/
palindrome_linked_list.cpp
File metadata and controls
65 lines (61 loc) · 1.48 KB
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
//program to detect if a singly linked list is palindrome or not
//problem link: https://leetcode.com/problems/palindrome-linked-list/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution
{
public:
void insertAtTail(ListNode*&head,ListNode*&tail,int val)
{
ListNode*newNode=new ListNode(val);
if(head==NULL)
{
head=newNode;
tail=newNode;
return;
}
tail->next=newNode;
tail=newNode;
}
void recursion(ListNode *&head, ListNode *cur)
{
if (cur->next == NULL)
{
head = cur;
return;
}
recursion(head, cur->next);
cur->next->next = cur;
cur->next = NULL;
}
bool isPalindrome(ListNode *head)
{
ListNode*listhead=NULL;
ListNode*listtail=NULL;
ListNode*tmp=head;
while(tmp!=NULL)
{
insertAtTail(listhead,listtail,tmp->val);
tmp=tmp->next;
}
recursion(listhead,listhead);
while(listhead!=NULL)
{
if(listhead->val!=head->val)
{
return false;
}
listhead=listhead->next;
head=head->next;
}
return true;
}
};