forked from mandliya/algorithms_and_data_structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
deleteLinkedlist.cpp
58 lines (52 loc) · 1.01 KB
/
deleteLinkedlist.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
/**
* Write a simple function to delete a linkedList
*/
#include <iostream>
struct Node {
int data;
Node * next;
Node( int d ) : data{ d }, next{ nullptr } { }
};
void insert( Node * & head, int data )
{
Node * newNode = new Node( data );
if ( head == nullptr ) {
head = newNode;
} else {
Node * temp = head;
while( temp->next != nullptr ) {
temp = temp->next;
}
temp->next = newNode;
}
}
void printList( Node * head )
{
while( head ) {
std::cout << head->data << "-->";
head = head->next;
}
std::cout << "NULL" << std::endl;
}
void deleteList( Node * & head )
{
while( head ) {
Node * nextNode = head->next;
delete( head );
head = nextNode;
}
}
int main()
{
Node * head = nullptr;
insert( head, 1 );
insert( head, 2 );
insert( head, 3 );
std::cout << "Current List: ";
printList( head );
std::cout << "Deleting List \n";
deleteList( head );
std::cout << "Printing List: ";
printList( head );
return 0;
}