FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
algorithm/PuzzleCoding/src/InsertCyclicList.java at master · wodgithub/algorithm · GitHub
wodgithub
algorithm
Repository navigation
Code
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
algorithm
/
PuzzleCoding
/
src
/
InsertCyclicList.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
73 lines (63 loc) · 1.88 KB
Breadcrumbs
algorithm
/
PuzzleCoding
/
src
/
InsertCyclicList.java
Copy path
File metadata and controls
73 lines (63 loc) · 1.88 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
/**
* Given a node from a cyclic linked list which has been sorted,
* write a function to insert a value into the list
* such that it remains a cyclic sorted list.
* The given node can be any single node in the list.
*/
public
class
InsertCyclicList
{
private
static
class
LinkedNode
{
public
int
value
;
public
LinkedNode
next
;
public
LinkedNode
() {
}
public
LinkedNode
(
int
v
) {
value
=
v
;
next
=
null
;
}
public
String
toString
() {
return
String
.
valueOf
(
value
);
}
public
LinkedNode
clone
() {
LinkedNode
n
=
new
LinkedNode
(
value
);
n
.
next
=
next
;
return
n
;
}
}
// end of linkednode class
public
static
void
main
(
String
[]
args
) {
LinkedNode
n1
=
new
LinkedNode
(
1
);
LinkedNode
n2
=
new
LinkedNode
(
2
);
LinkedNode
n4
=
new
LinkedNode
(
4
);
LinkedNode
n6
=
new
LinkedNode
(
6
);
n1
.
next
=
n2
;
n2
.
next
=
n4
;
n4
.
next
=
n6
;
n6
.
next
=
n1
;
int
x
=
5
;
// list must be sorted.
insertCyclicList
(
n1
,
x
);
LinkedNode
p
=
n1
;
do
{
System
.
out
.
print
(
p
.
toString
());
p
=
p
.
next
;
}
while
(!
p
.
equals
(
n1
));
}
public
static
void
insertCyclicList
(
LinkedNode
head
,
int
x
) {
if
(
head
==
null
) {
LinkedNode
n
=
new
LinkedNode
(
x
);
n
.
next
=
n
;
head
=
n
;
}
LinkedNode
p
=
head
.
clone
();
LinkedNode
prev
;
do
{
prev
=
p
;
p
=
p
.
next
;
if
(
x
<=
p
.
value
&&
x
>=
prev
.
value
)
break
;
// x is min or max of the list
if
((
prev
.
value
>
p
.
value
) && (
x
<
p
.
value
||
x
>
prev
.
value
))
break
;
}
while
(!
p
.
equals
(
head
));
LinkedNode
n
=
new
LinkedNode
(
x
);
prev
.
next
=
n
;
n
.
next
=
p
;
}
}
Back
|
FazBrowse Home
|
New Git URL