-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinkedList.c
68 lines (61 loc) · 1.31 KB
/
linkedList.c
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
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int val;
struct node *next;
} node;
node *create(int val) {
node *element = (node *)malloc(sizeof(int));
element->val = val;
element->next = NULL;
return element;
}
void *insertAtHead(node *head, int val) {
node *newHead = create(val);
newHead->next = head;
head = newHead;
}
void *insertAtEnd(node *head, int val) {
node *newTail = create(val);
if(head == NULL) {
head = newTail;
return;
}
node *h = head;
while(h->next != NULL) h = h->next;
h->next = newTail;
}
void insertAtIndex(node *head, int index, int val) {
node *el = create(val);
if(head == NULL) {
head = el;
return;
}
int count = 0;
node *h = head;
while (count + 1 < index && h->next != NULL) {
h = h->next;
count++;
}
if(h->next == NULL && count != index - 1){
h->next = el;
return;
}
el->next = h->next;
h->next = el;
}
node *reverse(node *head) {
if(head == NULL || head->next == NULL) return head;
node *prev = NULL;
node *cur = head;
while(cur != NULL) {
node *next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
return prev;
}
int main(int argc, char **argv) {
return 0;
}