-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem4.cpp
More file actions
139 lines (138 loc) · 3.21 KB
/
problem4.cpp
File metadata and controls
139 lines (138 loc) · 3.21 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
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
133
134
135
136
137
138
#include <iostream>
#include <iomanip>
#include <cmath>
#include <numeric>
//#include<bits/stdc++.h>
#include <string>
using namespace std;
#define endl '\n'
//#define haha cin.tie(0), cout.tie(0), cin.sync_with_stdio(0), cout.sync_with_stdio(0);
#define ll long long
struct node{
int data;
node*next=nullptr;
node*pre=nullptr;
node(int data):data(data){}
};
class doubly_linked_list{
private:node*tail{};
node*head{};
int length=0;
public:
node* delete_and_link(node*cur){
node*before=cur->pre;
node*after=cur->next;
link(before,after);
delete cur;
return before;
length--;
}
void link(node*first,node*second){
if(first!=nullptr){
first->next=second;
}
if(second !=nullptr)second->pre=first;
}
void print(){
for(node*cur=head;cur;cur=cur->next)cout<<cur->data<<" ";
}
void insert_sorted(int value) {
if (length == 0 || value <= head->data)insert_front(value);
else if (tail->data <= value)insert_end(value);
else {
for (node *cur = head; cur; cur=cur->next) {
if (value <= cur->data) {
embed_after(value,cur);
break;
}
}
}
}
void embed_after(int value,node*cur){
swap(value,cur->data);
node *after=cur->next;
node *ele=new node(value);
if(cur->next==nullptr){
insert_end(value);
}
else {
link(cur, ele);
link(ele,after);
length++;
}
}
void insert_front(int value){
node *ele =new node(value);
if(head==nullptr){
head=tail=ele;
}
else{
link(ele,head);
head=ele;
}
length++;
}
void insert_end(int value){
node *ele =new node(value);
if(head==nullptr){
head=tail=ele;
}
else {
link(tail,ele);
tail=ele;
tail->next=nullptr;
}
length++;
}
void delete_front(){
if(length==0){
cout<<"exception occurred"<<" ";
return;
}
else if(length==1){
delete head;
head=nullptr;
}
else{
node*after=head->next;
delete head;
head=after;
}
length--;
}
void delete_end(){
length--;
if(head== nullptr)return;
else if(length==1){
delete tail;
tail=nullptr;
}
else{
node*before=tail->pre;
delete tail;
tail=before;
tail->next=nullptr;
}
}
bool is_palindrome(){
if(head==nullptr)return "exception";
node*l=head,*r=tail;
while(head<=tail){
if(head->data!=tail->data)return false;
if(head->next!=nullptr) {
head = head->next;
tail=tail->pre;
}
else break;
}
return true;
}
};
int main(){
doubly_linked_list list;
list.insert_end(1);
list.insert_end(2);
list.insert_end(2);
list.insert_end(1);
cout<< list.is_palindrome();
}