-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathList_with_Circle_Insert.cpp
More file actions
105 lines (93 loc) · 1.69 KB
/
Copy pathList_with_Circle_Insert.cpp
File metadata and controls
105 lines (93 loc) · 1.69 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
#include "stdafx.h"
#include "iostream"
#include "vector"
#include "string"
#include "map"
#include <algorithm>
#include <stdlib.h>
#include <time.h>
#include <stack>
#include <sstream>
#include <iomanip>
#include <random>
#include <assert.h>
#include <iterator>
#include <queue>
using namespace std;
struct Node{
int val;
Node* next;
Node(int _v):val(_v){}
};
void insert(Node* &head, int val)
{
if(!head){
head=new Node(val);
return;
}
if(head->val>=val)
{
Node* tmp=new Node(val);
tmp->next=head;
head=tmp;
return;
}
Node* fastRunner=head;
Node* slowRunner=head;
while(true)
{
fastRunner=fastRunner->next;
fastRunner=fastRunner->next;
slowRunner=slowRunner->next;
if(fastRunner==slowRunner)break;
}
Node* cross=head;
while(cross!=slowRunner)
{
cross=cross->next;
slowRunner=slowRunner->next;
}
bool inCircle=false;
Node* runner=head;
while(runner->next->val<val)
{
if(runner==cross)
{
if(inCircle)
{
//insert before cross
Node* prevCross=cross;
while(prevCross->next!=cross)
{
prevCross=prevCross->next;
}
Node* tmp=new Node(val);
tmp->next=cross;
prevCross->next=tmp;
return;
}
else inCircle=true;
}
runner=runner->next;
}
Node* tmp=new Node(val);
tmp->next=runner->next;
runner->next=tmp;
}
void testInsert()
{
Node* head=new Node(1);
head->next=new Node(2);
head->next->next=new Node(2);
head->next->next->next=head->next;
insert(head, 0);
insert(head, 1);
insert(head, 2);
insert(head, 3);
insert(head, 4);
}
int _tmain(int argc, _TCHAR* argv[])
{
testInsert();
return 0;
}