-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsorted_insert_SLL.java
101 lines (88 loc) · 2.1 KB
/
sorted_insert_SLL.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
import java.util.Scanner;
/**
* Given a sorted LL and a data item, insert data item such that LL remains
* sorted even after insertion
*
* ip: 10->20->30->40, x=25
* op: 10->20->25->30->40
*
* ip: 10->25, x=5
* op: 5->10->25
*
* ip: 10->20, x=30
* op: 10->20->30
*
* ip: null, x= 10
* op: 10
*
* we traverse the list, for traversing let's have a node called curr, it will
* initially point to first node
* we will compare curr's next data item with x
* if(curr.next < x)
* move to next node
* if(curr.next > x)
* insert a node after curr
*
* newNode.next = curr.next
* curr.next = newNode
*
* Time: depends on position where we are inserting
* if x is smaller than head's data it's O(1)
* but if x is greater than tail's data it's θ(n)
*
* in general, if we inserting in position 'pos', time is θ(pos)
*/
class Node {
Node next;
int data;
Node(int x){
data = x;
next = null;
}
}
class sorted_insert_SLL {
public static void main(String[] args) {
Node head = new Node(10);
head.next = new Node(20);
head.next.next = new Node(30);
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
printList(head);
head = sortedInsert(head, x);
printList(head);
sc.close();
}
public static Node sortedInsert(Node head, int x) {
Node newNode = new Node(x);
if (head == null)
return null;
if (x < head.data) {
newNode.next = head;
head = newNode;
return head;
}
Node curr = head;
while (curr.next != null && curr.next.data < x) {
curr = curr.next;
}
newNode.next = curr.next;
curr.next = newNode;
return head;
}
public static void printList(Node head) {
Node traverse = head;
while (traverse != null) {
System.out.print(traverse.data + "->");
traverse = traverse.next;
}
System.out.print("null\n");
}
}
/**
* ip:
* 5
*
* op:
* 10->20->30->null
* 5->10->20->30->null
*/