Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- typedef struct Node {
- int val;
- struct Node *next;
- } Node;
- // Длина списка
- int counter(Node **head) {
- int counter = 0;
- Node *current = *head;
- if (*head == NULL) exit(-1);
- else {
- counter++;
- while (current->next != NULL) {
- counter++;
- current = current->next;
- }
- }
- return counter;
- }
- // Печать списка
- void print(Node *head) {
- while (head != NULL) {
- printf("%d ", head->val);
- head = head->next;
- }
- }
- // Добавление элемента в конец
- void pushBack(Node **head, int data) {
- Node *tmp = (Node *) malloc(sizeof(Node));
- tmp->val = data;
- tmp->next = NULL;
- Node *current = *head;
- if (*head == NULL) *head = tmp;
- else {
- while (current->next != NULL) current = current->next;
- current->next = tmp;
- }
- }
- // Удаление элемента из конца списка
- void popBack(Node **head) {
- Node *current = *head;
- if (*head == NULL) exit(-1);
- else {
- while (current->next->next != NULL) current = current->next;
- free(current->next);
- current->next = NULL;
- }
- }
- // Вставка элемента
- void insert(Node **head, int ind, int value) {
- int count = counter(head);
- if (count > 0 && ind <= count) {
- Node *current = *head;
- Node *tmp = (Node *)malloc(sizeof(Node));
- tmp->val = value;
- for (int i = 1; i < ind-1; i++) current = current->next;
- tmp->next = current->next;
- current->next = tmp;
- } else exit(-1);
- }
- // Удаление элемента
- void delete(Node **head, int ind) {
- int count = counter(head);
- if ( count > 0 && ind < count) {
- Node *current = *head;
- Node *prev = *head;
- for (int i = 1; i < ind-1; i++) prev = prev->next;
- for (int i = 1; i < ind; i++) current = current->next;
- prev->next = current->next;
- free(current);
- }
- }
- int main() {
- Node *head = NULL;
- int count;
- printf("Заполнение массива с помощью функции pushBack \n");
- for (int i = 1; i <= 15; i++) pushBack(&head, i);
- print(head);
- printf("\nУдаление последнего элемента\n");
- popBack(&head);
- print(head);
- printf("\nВставка элемента по индексу \n");
- insert(&head, 5, 5);
- print(head);
- printf("\nУдаление элемента по индексу\n");
- delete(&head, 5);
- print(head);
- count = counter(&head);
- printf("\nДлина списка - %d \n", count);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement