-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSortedLinkedList.java
100 lines (83 loc) · 1.68 KB
/
SortedLinkedList.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
/*
Copyright (C) Deepali Srivastava - All Rights Reserved
This code is part of DSA course available on CourseGalaxy.com
*/
package sortedLinkedList;
import java.util.Scanner;
public class SortedLinkedList
{
private Node start;
public SortedLinkedList()
{
start=null;
}
public void insertInOrder(int data)
{
Node temp=new Node(data);
/*List empty or new node to be inserted before first node*/
if(start==null || data<start.info)
{
temp.link=start;
start=temp;
return;
}
Node p=start;
while(p.link!=null && p.link.info <= data)
p=p.link;
temp.link=p.link;
p.link=temp;
}/*End of insertInOrder()*/
public void createList()
{
int i,n,data;
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number of nodes : ");
n = scan.nextInt();
if(n==0)
return;
for(i=1; i<=n; i++)
{
System.out.print("Enter the element to be inserted : ");
data = scan.nextInt();
insertInOrder(data);
}
}/*End of createList()*/
public void search(int x)
{
if(start==null)
{
System.out.println("List is empty");
return;
}
Node p=start;
int position=1;
while(p!=null && p.info<=x)
{
if(p.info==x)
break;
position++;
p=p.link;
}
if(p==null || p.info!=x)
System.out.println(x + " not found in list");
else
System.out.println(x + " is at position " + position);
}/*End of search()*/
public void displayList()
{
Node p;
if(start==null)
{
System.out.println("List is empty");
return;
}
System.out.print("List is : ");
p=start;
while(p!=null)
{
System.out.print(p.info + " ");
p=p.link;
}
System.out.println();
}/*End of displayList()*/
}