-
Notifications
You must be signed in to change notification settings - Fork 0
/
eg_SingleLinkedList.cpp
83 lines (66 loc) · 1.4 KB
/
eg_SingleLinkedList.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
#include <iostream>
#include <cstdlib>
using namespace std;
typedef struct Node
{
int data;
struct Node * next;
}Node;
void insert(Node ** head, int newData);
void printList(Node * head);
void deleteNode(Node ** head, int position);
int main()
{
Node * head = NULL;
insert(&head, 7);
insert(&head, 1);
insert(&head, 3);
insert(&head, 8);
insert(&head, 2);
insert(&head, 6);
printList(head);
deleteNode(&head, 0);
printList(head);
deleteNode(&head, 2);
printList(head);
return 0;
}
void insert(Node ** head, int newData)
{
Node * newNode = (Node *) malloc(sizeof(Node));
newNode -> data = newData;
newNode -> next = *head;
*head = newNode;
}
void printList(Node * head)
{
while(head != NULL)
{
cout << head->data << " ";
head = head->next;
}
cout << endl;
}
void deleteNode(Node ** head, int position)
{
if(*head == NULL)
{
cout << "List is empty, hence unable to delete any element" << endl;
return;
}
Node * temp = *head;
if(position == 0)
{
// deleting head
*head = temp -> next;
free(temp);
return;
}
for(int i = 0; temp != NULL && i<(position-1) ; i++)
temp = temp->next;
if(temp == NULL || temp->next == NULL)
return;
Node * next = temp->next->next;
temp->next = next;
free(temp->next);
}