forked from Rohitkkpandey/Data_struct_geek4geek
-
Notifications
You must be signed in to change notification settings - Fork 1
/
linkedList.cpp
103 lines (77 loc) · 1.6 KB
/
linkedList.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#include<iostream>
#include<stdlib.h>
#include<stdio.h>
using namespace std;
struct Node{
int data;
struct Node* next;
Node(int x){
data=x;
next=NULL;
}
};
Node* insertAtEnd(int i, Node* head){
struct Node* node=new Node(i);
struct Node* current;
current=head;
if(head==NULL)
return node;
while(current->next!=node){
if (current->next!=NULL)
current=current->next;
else
current->next=node;
}
return head;
}
//this part just skips a node
// Node* skipNode(Node* head, int y){
// struct Node* current=new Node(0);
// current=head;
// if(y==1)
// return head->next;
// for(int i=1; i<y-1; i++){
// current=current->next;
// }
// current->next = current->next->next;
// return head;
// }
//this part deletes a node
Node* deleteNode(Node* head, int y){
struct Node* current=NULL;
struct Node* temp=NULL;
current=head;
temp=head->next;
if(y==1)
return head->next;
for(int i=1; i<y-1; i++){
current=current->next;
temp=temp->next;
}
current->next = current->next->next; //or current->next=temp->next;
delete temp;
return head;
}
void printList(Node* head){
while(head!=NULL){
cout<<head->data<<" ";
head=head->next;
}
cout<<"\n";
}
int main(){
cout<<"input size of linked list, then eliments of linked list, then no, of which eliment is to be deleted. \n";
int x,y;
cin >> x;
struct Node* head=NULL;
while(x--){
int i;
cin >> i;
head=insertAtEnd(i, head);
}
cin >> y;
if(y!=0)
head=deleteNode(head, y);
printList(head);
return 0;
}