-
Notifications
You must be signed in to change notification settings - Fork 0
/
55.LinkedList_insertIntoSorted_isSorted.cpp
73 lines (66 loc) · 1.26 KB
/
55.LinkedList_insertIntoSorted_isSorted.cpp
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
#include<iostream>
using namespace std;
struct node{
int data;
node* next;
};
node* first = new node;
bool issorted(node* p){
int min = p->data;
while(p!=NULL){
if(min>p->data){
return false;
}
else{
p = p->next;
}
}
return true;
}
void create(node* p){
int num;
cout<<"enter number of elements in linked list: ";
cin>>num;
cout<<"enter "<<num<<" elements: ";
cin>>p->data;
for(int i=1;i<num;i++){
node* temp = new node;
cin>>temp->data;
temp->next = p->next;
p->next = temp;
p = temp;
}
}
void display(node *p){
while(p!=NULL){
cout<<p->data<<" ";
p = p->next;
}
}
void insert_sorted(node* p, int x){
//assuming it is sorted
node *q = new node;
q = NULL;
while(p && x>p->data){
q = p;
p = p->next;
}
node* temp = new node;
temp->data = x;
temp->next = p;
q->next = temp;
}
int main(){
create(first);
display(first);
insert_sorted(first,2);
cout<<endl;
display(first);
cout<<endl;
cout<<issorted(first);
node* some_other = new node;
create(some_other);
display(some_other);
cout<<endl;
cout<<issorted(some_other);
}