-
Notifications
You must be signed in to change notification settings - Fork 0
/
linkedList.cpp
69 lines (58 loc) · 1.64 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
#include <iostream>
using namespace std;
//Defining the node
struct node {
int data;
node * link;
};
node *head=NULL;
//Defining a function to add a node after a previous node
node* addNode(int num, node * prev=NULL){
// creating the node
node *newNode = new node;
newNode->data = num;
newNode->link = NULL;
//check if the LL is empty
if(head == NULL)
head = newNode;
// adding node at head
else if(prev==NULL) {
newNode->link = head;
head =newNode;
}
//adding node after previous
else{
node *temp=prev->link;
prev->link =newNode;
newNode->link = temp;
}
return newNode;
}
// Now implement a function named deleteNode to delete a node (data)
void show(){
node * curr = head;
while(curr != NULL) {
cout<< curr->data << " ";
curr = curr->link;
}
cout<<"\n\n";
}
int main(){
// Keeping some elements into an array
int a[5]={3,2,5,11,4};
for(int i=0; i<5; i++) {
//adding the elements at head
addNode(a[i]);
}
show();
// initializing another Linked List
head =NULL;
node * last=NULL;
for(int i=0; i<5; i++) {
//adding the elements after last node
last=addNode(a[i],last);
}
show();
// Call the function deleteNode here and show updated list
return 0;
}