-
Notifications
You must be signed in to change notification settings - Fork 0
/
asteroidCollision.cpp
105 lines (105 loc) · 1.88 KB
/
asteroidCollision.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
#include<map>
#include<iostream>
#include<vector>
using namespace std;
typedef struct List
{
int val;
struct List* next;
struct List* prev;
}list;
struct LinkedList
{
list* head;
list* tail;
};
void insert(struct LinkedList* l1,int val)
{
list* temp=(list*)calloc(1,sizeof(list));
temp->val=val;
temp->prev=NULL;
temp->next=NULL;
if(!l1->head)
{
l1->head=temp;
l1->tail=l1->head;
}
else
{
temp->prev=l1->tail;
l1->tail->next=temp;
l1->tail=temp;
}
}
void remove(LinkedList* ls,list* ptr)
{
if(ptr==ls->head)
{
ls->head=ptr->next;
if(ptr->next)
ptr->next->prev=NULL;
}
else
{
if(ptr->prev)
ptr->prev->next=ptr->next;
if(ptr->next)
ptr->next->prev=ptr->prev;
}
// free(ptr);
}
vector<int> asteroidCollision(vector<int>& asteroids)
{
//map<int,list*> mp;
int start=0;
while(start<asteroids.size()&&asteroids[start]<0)
++start;
struct LinkedList* l1=(struct LinkedList*)calloc(1,sizeof(LinkedList));
l1->head=NULL;
l1->tail=NULL;
for(int i=start;i<asteroids.size();++i)
insert(l1,asteroids.at(i));
list* temp=l1->head;
while(temp!=NULL)
{
//cout<<temp->val<<"\n";
if(temp->val<0)
{
if(temp==l1->head||(temp->prev->val<0))
temp=temp->next;
else if(abs(temp->prev->val)>abs(temp->val))
{
temp=temp->prev;
remove(l1,temp->next);
}
else if(abs(temp->val)>abs(temp->prev->val))
remove(l1,temp->prev);
else
{
temp=temp->prev;
remove(l1,temp->next);
remove(l1,temp);
}
}
else
temp=temp->next;
}
vector<int> ret;
for(int j=0;j<start&&j<asteroids.size();++j)
ret.push_back(asteroids[j]);
temp=l1->head;
while(temp!=NULL)
{
cout<<temp->val<<"\n";
ret.push_back(temp->val);
temp=temp->next;
}
return ret;
}
int main(int argc, char const *argv[])
{
vector<int> asteroids={5,-15};
vector<int> ret=asteroidCollision(asteroids);
cout<<ret.size();
return 0;
}