-
Notifications
You must be signed in to change notification settings - Fork 4
/
linked_list.cpp
72 lines (64 loc) · 1.18 KB
/
linked_list.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
// C code to delete a node from linked list
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int number;
struct Node* next;
} Node;
void Push(Node** head, int A)
{
Node* n = malloc(sizeof(Node));
n->number = A;
n->next = *head;
*head = n;
}
void deleteN(Node** head, int position)
{
Node* temp;
Node* prev;
temp = *head;
prev = *head;
for (int i = 0; i < position; i ) {
if (i == 0 && position == 1) {
*head = (*head)->next;
free(temp);
}
else {
if (i == position - 1 && temp) {
prev->next = temp->next;
free(temp);
}
else {
prev = temp;
// Position was greater than
// number of nodes in the list
if (prev == NULL)
break;
temp = temp->next;
}
}
}
}
void printList(Node* head)
{
while (head) {
printf("[%i] [%p]->%p\n", head->number, head,
head->next);
head = head->next;
}
printf("\n\n");
}
// Drivers code
int main()
{
Node* list = malloc(sizeof(Node));
list->next = NULL;
Push(&list, 1);
Push(&list, 2);
Push(&list, 3);
printList(list);
// Delete any position from list
deleteN(&list, 1);
printList(list);
return 0;
}