test

C code posted by test
created at 14 Oct 12:37

Edit | Back
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
84
85
86
87
88
89
90
#include <stdio.h>
#include <stdlib.h>

typedef struct l1 {
  struct l1* next;
  int key;
} l1;

l1* head = NULL;

l1* insert_head(int key) {
  l1* p;
  p = (l1*) malloc(sizeof(struct l1));
  if(p == NULL) {
    printf("No memory\n");
    return NULL;
  }
  p->key = key;
  p->next = head;
  head = p;
  return p;
}

l1* insert_tail(int key) {
  l1** tail;
  l1* p;
  
  tail = &head;
  p = (l1*) malloc(sizeof(struct l1));
  if(p == NULL) {
    printf("No memory\n");
    return NULL;
  }
  
  p->key = key;
  p->next = NULL;
  
  while(*tail != NULL) 
    tail = &((*tail)->next);
  
  *tail = p;
  
  return p;
}

void remove_item(int key) {
  l1** parent;
  l1* p;
  
  p = head;
  parent = &head;
  
  while(p != NULL) {
    if(p->key == key) {
      *parent = p->next;
      free(p);
      p = *parent;
    } else {
      parent = &(p->next);
      p = p->next;
    }
  }
}

void print(void) {
  l1* p;
  p = head;
  if(p != NULL) {
    for(; p!=NULL; p = p->next) {
      printf("%d ", p->key);
    }
  } else {
    printf("L1 is empty!");
  }
  printf("\n");
}

int main(int argc, char** argv) {
  print();
  insert_tail(1);
  insert_tail(1);
  insert_tail(1);
  insert_head(100);
  insert_tail(1);
  insert_tail(2);
  insert_tail(1);
  print();
  remove_item(1);
  print();
}
1.34 KB in 3 ms with coderay