-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinkedliststruct.cpp
88 lines (77 loc) · 2.1 KB
/
linkedliststruct.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define _z ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
struct Node{
int data;
Node* next;
};
class LinkedList{
private:
Node* head;
public:
LinkedList(){
head = NULL;
}
void addAtHead(int d){
Node* newNode = new Node();
newNode -> data = d;
newNode -> next = head;
head = newNode;
}
void addAtTail(int d){
Node* newNode = new Node();
newNode -> data = d;
newNode -> next = NULL;
if(head == NULL){
head = newNode;
}
else{
Node* temp = head;
while(temp!=NULL){
temp = temp -> next;
}
temp -> next = newNode;
}
}
void addAtAnypos(int d, int pos){
Node* newNode = new Node;
newNode-> data = d;
newNode->next = NULL;
if(pos==1){
//addAtHead(d);
newNode -> data = d;
newNode -> next = head;
newNode = head;
}
else{
Node* temp = new Node;
for(int i=0; i<pos-1 && temp!=NULL; i++){
temp = temp -> next;
}
if(temp == NULL){
cout<<"Invaid position"<<endl;
} else {
newNode -> next = temp -> next;
newNode = temp;
}
}
}
void print(){
Node* temp = new Node;
while(temp != NULL){
cout<<temp ->data<<" ";
temp = temp -> next;
}
cout<<endl;
}
};
int main(){
LinkedList myList;
myList.addAtHead(5);
myList.addAtHead(10);
myList.addAtTail(20);
myList.addAtAnypos(15, 2);
myList.print();
return 0;
}