-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathSortedInsert.java
92 lines (85 loc) · 2.86 KB
/
SortedInsert.java
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
// Sorted insert for circular linked list
// Algorithm:
// Allocate memory for the newly inserted node and put data in the newly allocated node.
// Let the pointer to the new node be new_node. After memory allocation,
// following are the three cases that need to be handled.
// 1) Linked List is empty:
// a) since node is the only node in CLL, make a self loop.
// node->next = node;
// b) change the head pointer to point to new node.
// head = node;
// 2) New node is to be inserted just before the head node:
// (a) Find out the last node using a loop.
// while(current.next != head)
// current = current.next;
// (b) Change the next of last node.
// current.next = node;
// (c) Change next of new node to point to head.
// node.next = head;
// (d) change the head pointer to point to new node.
// head = node;
// 3) New node is to be inserted somewhere after the head:
// (a) Locate the node after which new node is to be inserted.
// while ( current.next!= head &&
// current.next.data < node.data)
// { current = current.next; }
// (b) Make next of node as next of the located pointer
// node.next = current.next;
// (c) Change the next of the located pointer
// current.next = node;
class Node{
int data;
Node next;
Node(int d){
data = d;
next = null;
}
}
class CircularLinkedList{
Node head;
CircularLinkedList(){
head = null;
}
public void sortAndInsert(Node node){
Node current = head;
if(current == null){ // step 1.
node.next = node;
head = node;
}
else if(node.data < current.data){ // step 2.
/* If value is smaller than head's value then
we need to change next of last node */
while(current.next != head)
current = current.next;
current.next = node;
node.next = head;
head = node;
}
else{ //step 3.
while(current.next != head && node.data >= current.data)
current = current.next;
node.next = current.next;
current.next = node;
}
}
public void print(){
if(head != null){
Node node = head;
do{
System.out.print(node.data + "->");
node = node.next;
}while(node != head);
}
System.out.println("null");
}
public static void main(String args[]){
CircularLinkedList c = new CircularLinkedList();
int array[] = new int[] {12,23,24,5,67,34};
Node temp = null; //empty CircularLinkedList
for(int i=0;i<array.length;i++){
temp = new Node(array[i]);
c.sortAndInsert(temp);
}
c.print();
}
}