-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSorted-insert-for-circular-Linked-list.java
133 lines (110 loc) · 2.9 KB
/
Sorted-insert-for-circular-Linked-list.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
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
/*
Definition for singly Link List Node
class Node
{
int data;
Node next;
Node(int x){
data = x;
next = null;
}
}
You can also use the following for printing the link list.
Node.printList(Node node);
*/
//{ Driver Code Starts
import java.util.Scanner;
// Node Class
class Node {
int data;
Node next;
Node(int x) {
data = x;
next = null;
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
Node start = null;
Node temp=null, r = null;
// Create linked list from the array arr[].
// Created linked list will be 1->2->11->56->12
if (n > 0) {
int arr = sc.nextInt();
temp = new Node(arr);
start = temp;
r = start;
}
for (int i = 0; i < n - 1; i++) {
int arr = sc.nextInt();
temp = new Node(arr);
r.next = temp;
r = r.next;
}
if (n > 0)
{
temp.next = start;
r = temp;
}
int x = sc.nextInt();
Solution ob = new Solution();
start = ob.sortedInsert(start, x);
printList(start);
r = start;
while (r != start.next) {
temp = start;
start = start.next;
temp = null;
}
temp = null;
}
}
/* Function to print Nodes in a given linked list */
static void printList(Node start) {
Node temp;
if (start != null) {
temp = start;
do {
System.out.print(temp.data + " ");
temp = temp.next;
} while (temp != start);
System.out.println();
}
}
}
// } Driver Code Ends
//User function Template for Java
class Solution {
public Node sortedInsert(Node head, int data) {
// code here
Node cur = head;
Node newNode = new Node(data);
// CASE 1 : Empty Linked List
if(head == null){
newNode.next = newNode;
return newNode;
}
// CASE 2 : New Node is smaller than head
else if(data <= head.data){
while(cur.next != head){
cur = cur.next;
}
cur.next = newNode;
newNode.next = head;
return newNode;
}
// CASE 3 : New Node can be inserted in between the list
else{
while(cur.next != head && data > cur.next.data){
cur = cur.next;
}
newNode.next = cur.next;
cur.next = newNode;
return head;
}
}
}