94 lines
1.5 KiB
C
94 lines
1.5 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
|
|
typedef struct Student student;
|
|
struct Student {
|
|
int sid;
|
|
struct Student *next;
|
|
};
|
|
|
|
void insert(student **head, int idx, uint sid) {
|
|
student *new = malloc(sizeof(student));
|
|
new->sid = sid;
|
|
|
|
int i = 0;
|
|
|
|
student *prev = NULL, *cur = *head;
|
|
|
|
for (int i = 0;; i++) {
|
|
if (i == idx) {
|
|
if (prev != NULL)
|
|
prev->next = new;
|
|
else
|
|
*head = new;
|
|
new->next = cur;
|
|
return;
|
|
}
|
|
|
|
if (cur == NULL)
|
|
return;
|
|
|
|
prev = cur;
|
|
cur = cur->next;
|
|
}
|
|
|
|
printf("Index %d does not exist\n", idx);
|
|
return;
|
|
}
|
|
|
|
void delete (student **head, int idx) {
|
|
student *prev = NULL, *cur = *head;
|
|
|
|
for (int i = 0; cur != NULL; i++) {
|
|
if (i == idx) {
|
|
if (prev != NULL)
|
|
prev->next = cur->next;
|
|
else
|
|
*head = cur->next;
|
|
free(cur);
|
|
return;
|
|
}
|
|
prev = cur;
|
|
cur = cur->next;
|
|
}
|
|
|
|
printf("Index %d does not exist\n", idx);
|
|
return;
|
|
}
|
|
|
|
void reverse(student **head) {
|
|
student *prev = NULL, *cur = *head;
|
|
|
|
while (cur->next != NULL) {
|
|
student *next = cur->next;
|
|
cur->next = prev;
|
|
prev = cur;
|
|
cur = next;
|
|
}
|
|
|
|
cur->next = prev;
|
|
|
|
*head = cur;
|
|
return;
|
|
}
|
|
|
|
int main() {
|
|
student *head = NULL;
|
|
insert(&head, 0, 1);
|
|
insert(&head, 1, 2002);
|
|
insert(&head, 2, -9);
|
|
insert(&head, 3, 52);
|
|
insert(&head, 1, 4);
|
|
delete (&head, 2);
|
|
reverse(&head);
|
|
|
|
while (head != NULL) {
|
|
printf("%d ", head->sid);
|
|
head = head->next;
|
|
}
|
|
|
|
// free
|
|
while (head != NULL)
|
|
delete(&head, 0);
|
|
}
|