-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedList.c
More file actions
77 lines (68 loc) · 1.26 KB
/
LinkedList.c
File metadata and controls
77 lines (68 loc) · 1.26 KB
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
#include <stdio.h>
#include <stdlib.h>
#include "LinkedList.h"
struct Node *newList(void)
{
struct Node *newNode = malloc(sizeof(struct Node));
if (newNode != NULL)
newNode->next = NULL;
return newNode;
}
struct Node *delete(struct Node *prev)
{
struct Node *nextNode = prev->next;
if (nextNode == NULL)
return NULL;
prev->next = nextNode->next;
nextNode->next = NULL;
return nextNode;
}
struct Node *insert(struct Node *prev, void *data)
{
struct Node *newNode = malloc(sizeof(struct Node));
if (newNode != NULL) {
newNode->data = data;
newNode->next = prev->next;
prev->next = newNode;
}
return newNode;
}
int length(struct Node *head)
{
struct Node *curr = head;
int len = 0;
while (curr->next != NULL) {
len++;
curr = curr->next;
}
return len;
}
void printList(struct Node *head)
{
struct Node *curr = head->next;
while (curr != NULL) {
printData(curr->data);
printf(" ");
curr = curr->next;
}
printf("\n");
}
struct Node *getNode(struct Node *head, int i)
{
struct Node *curr = head;
while (i > 0 && curr != NULL) {
curr = curr->next;
i--;
}
return curr;
}
void deleteList(struct Node *head)
{
struct Node *deleted;
while (length(head) > 0) {
deleted = delete(head);
free(deleted->data);
free(deleted);
}
free(head);
}