Вы находитесь на странице: 1из 26

Министерство Образования и Исследований 

Республики Молдова 
 
Технический Университет Молдовы 
 
Кафедра «Автоматика и информационные технологии»
              
 
 
 
Отчет 
по лабораторной работе Nr.8-9. 
по Структурам Данных и Алгоритмам

Тема: Изучение возможностей и средств языка Си для реализации и


использования основных операций обработки односвязного списка. 

                                         Вариант 5  


 
 
 
 

 
Выполнил ст.гр. SI-                           
 
Проверил                                                  

                              Кишинев – 202X


1
Лабораторная работа Nr.8-9. 
Тема работы: Обработка массива структур и использование файлов на языке Си

Цель работы: Программирование алгоритмов для обработки массива структур, используя


функции, указатели, динамическое выделение памяти и файлы на языке Си.

Задание:

Задание: Составить три файла на языке Си для реализации и использования АТД «Односвязный
список» с обеспечением указанных в теме лабораторной работы операций обработки.

1. Заголовочный файл с расширением .h для описания структуры данных элемента списка (по
вариантам), а также для прототипов функций, обеспечивающих основные операции
обработки списка.
2. Файл с расширением .cpp для определений функций (текстов функций), объявленных в
заголовочном файле.
3. Файл пользователя - функцию mаin () для обработки списка с помощью указанных в теме
лабораторной работы операций с выводом на экран меню этих операций.
4. Дополнить три файла, составленных в лабораторной работе 8 для реализации и
использования АТД «Односвязный список» с целью обеспечения всех перечисленных
специальных операций обработки списка

Мой код:
___________________________________main.cpp_________________________________________

#include "header.h"

int main()

int choice;

int Count;

Node* Head = NULL;

Node* Head2 = NULL;

2
do

printf("\n ----- Main Menu: -----\n");

printf(" 1. Create a new head node\n");

printf(" 2. Print list\n");

printf(" 3. Add a new node to the tail\n");

printf(" 4. Swap two elements\n");

printf(" 5. Sort the elements\n");

printf(" 6. Search for elements\n");

printf(" 7. Edit element\n");

printf(" 8. Remove element\n");

printf(" 9. Free memory\n");

printf(" 10. Save to file\n");

printf(" 11. Read from file\n");

printf(" 12. Split the list\n");

printf(" 13. Merge the list\n");

printf(" 14. Show memory addresses\n");

printf(" 15. Show list count\n");

printf(" 16. Exit\n");

printf("\nChoose an option from the menu:\n> ");

scanf("%d", &choice);

switch(choice)

case 1:

FreeMemory(Head);

Head = CreateNode();

3
break;

case 2: PrintList( Head , Head2); break;

case 3: AddNewToTail( Head ); break;

case 4: SwitchTwoElements( Head ); break;

case 5: SortElements( Head ); break;

case 6: SearchElements( Head ); break;

case 7: EditElement( Head ); break;

case 8: RemoveElement( Head ); break;

case 9: FreeAllElements( Head ); break;

case 10: SaveToFile( Head ); break;

case 11: ReadFromFile( Head ); break;

case 12: SplitList( Head, Head2 ); break;

case 13: MergeList( Head, Head2 ); break;

case 14: ShowAddress( Head ); break;

case 15: ShowCount( Head ); break;

case 16: {

if (Head != NULL) FreeMemory(Head);

if (Head2 != NULL) FreeMemory(Head2);

return 0;

} while (1);

getch();

return 0;

4
}

_______________________________header.h______________________________________________

#include <stdio.h>

#include <iostream>

#include <limits>

#include <string.h>

#include <stdlib.h>

#include <conio.h>

#include <time.h>

typedef struct _node

char Name[50];

char Country[50];

char Manufacturer[50];

int Vendorcode;

int Price;

struct _node* Next = NULL;

} Node;

void PrintList( Node *head, Node *head2 );

void AddNewToTail( Node *head );

void SwitchTwoElements( Node *&head );

void SortElements( Node *&head );

void SearchElements( Node *start );

void EditElement( Node *head );

void RemoveElement( Node *&head );

5
void FreeAllElements( Node *&head );

void SaveToFile(Node *&head );

void ReadFromFile( Node *&head );

void SplitList( Node *&head, Node *&head2 );

void MergeList( Node *&head, Node *&head2 );

void ShowAddress( Node *head );

void ShowCount( Node *head );

Node *CreateNode();

Node *GetLastNodeFromHead( Node *head );

void Swap( Node *&head, Node *node1, Node *node2 );

Node *GetNthNodeFromHead( Node *head, int n );

int GetIndexOfNodeFromHead( Node *head, Node *node );

void FreeMemory( Node *&head );

___________________________________func.cpp__________________________________________

#include "header.h"

void Print( Node *head )


{
Node *temp = head;
int i = 0;

printf(" -------------------------------------------------------------------------------------------------------\n");
printf(" | # | Name | Country | Manufacturer | Vendor code | Price |\n");
printf(" -------------------------------------------------------------------------------------------------------\n");

do {
printf(" | %d |%-12s |%-14s |%-12s |%5d |%5d | \n",
i,
temp->Name,
temp->Country,
temp->Manufacturer,
temp->Vendorcode,
temp->Price );

temp = temp->Next;
6
i++;
} while ( temp );

printf(" -------------------------------------------------------------------------------------------------------\n");
}
void PrintList( Node *head, Node *head2 )
{
printf("\n ----- 2.Print list. -----\n\n");

if( head == NULL )


{
printf("\n[Error] Head doesn't exist.\n\n");
return;
}

Print( head );

if( head2 != NULL )


{
printf("\n");
Print( head2 );
}
}
void AddNewToTail( Node *head )
{
printf("\n ----- 3. Add a new node to the tail. -----\n\n");

if(head == NULL)
{
printf("\n[Error] Head doesn't exist.\n\n");
return;
}

Node *last = GetLastNodeFromHead( head );


last->Next = CreateNode();
}

void SwitchTwoElements( Node *&head )


{
printf("\n ----- 4. Swap two elements. -----\n\n");

if(head == NULL)
{
printf("\nFatal: Head doesn't exist.\n\n");
return;

7
}

int buff = 0;
printf("\nSelect element #1 that you want to swap.\n> ");
scanf("%d", &buff);

Node *node1 = GetNthNodeFromHead(head, buff);


if(node1 == NULL)
{
printf("\nFatal: Element %d doesn't exist in the list.\n\n", buff);
return;
}

printf("\nSelect element #2 that you want to swap.\n> ");


scanf("%d", &buff);

Node *node2 = GetNthNodeFromHead(head, buff);


if(node2 == NULL)
{
printf("\nFatal: Element %d doesn't exist in the list.\n\n", buff);
return;
}

Swap(head, node1, node2);


}

void SortElements( Node *&head )


{
printf("\n ----- 5. Sort elements. -----\n\n");

if(head == NULL)
{
printf("\nFatal: Head doesn't exist.\n\n");
return;
}

int prop;
printf("\nSelect the property by which to sort:\n");
printf(" 1. Name\n");
printf(" 2. Country\n");
printf(" 3. Manufacturer\n");
printf(" 4. Vendorcode\n");
printf(" 5. Price\n");
printf("> ");
scanf("%d", &prop);

8
if(prop < 1 || prop > 5)
{
printf("\nFatal: Invalid property option.");
return;
}

int method;
printf("\nSelect the method by which to sort:\n");
printf(" 1. Descending \n");
printf(" 2. Ascending \n");
printf("> ");
scanf("%d", &method);
if(method < 1 || method > 2)
{
printf("\nFatal: Invalid method option.");
return;
}

int isDESC = method == 1;


int isASC = method == 2;

Node *a, *b, *p, *h = NULL;

for (Node *i = head; i != NULL; )


{
a = i;
i = i->Next;
b = h;

for (p = NULL; b != NULL; )


{
int diff = 0;
switch(prop)
{
case 1: diff = strcmp(a->Name, b->Name); break;
case 2: diff = strcmp(a->Country, b->Country); break;
case 3: diff = strcmp(a->Manufacturer, b->Manufacturer); break;
case 4: diff = a->Vendorcode - b->Vendorcode; break;
case 5: diff = a->Price - b->Price; break;
}

if((isDESC && diff > 0) || (isASC && diff < 0))


break;

p = b;
9
b = b->Next;
}

if (p == NULL)
{
a->Next = h;
h = a;
}
else
{
a->Next = b;
p->Next = a;
}
}

if ( h != NULL )
{
head = h;
}
}

void SearchElements( Node *start )


{
printf("\n ----- 6. Search for an element in array -----\n\n");

int prop;
printf("\nSelect the property to search elements by:\n");
printf(" 1. Name\n");
printf(" 2. Country\n");
printf(" 3. Manufacturer\n");
printf(" 4. Vendorcode\n");
printf(" 5. Price\n");
printf("> ");
scanf("%d", &prop);
if(prop < 1 || prop > 5)
{
printf("\n[Error] Invalid property option.");
return;
}

char buffer[32];
printf("\nInput the query:\n> ");
fflush(stdin);
gets(buffer);

10
// cast in case we need to compare numeric values
int ibuff = strtol(buffer, NULL, 10);

printf("\nFound Entries:\n\n");
int i = 0;

do
{
int bFlag = 1;

switch(prop)
{
case 1: bFlag = strcmp(start->Name, buffer) == 0; break;
case 2: bFlag = strcmp(start->Country, buffer) == 0; break;
case 3: bFlag = strcmp(start->Manufacturer, buffer) == 0; break;
case 4: bFlag = start->Vendorcode == ibuff; break;
case 5: bFlag = start->Price == ibuff; break;
}

if(bFlag)
{
printf("- #%d \"%s \" (country: \"%s\") (manufacturer: \"%s\") (vendorcode: %d)
(price: %d)\n",
i,
start->Name,
start->Country,
start->Manufacturer,
start->Vendorcode,
start->Price);
}

i++;
start = start->Next;

} while (start != NULL);


}

void EditElement( Node *head )


{
printf("\n ----- 7. Editing an array element -----\n\n");

printf("\nInput the index of the element to edit:\n> ");


int i;
scanf("%d", &i);

11
Node *node = GetNthNodeFromHead(head, i);
if( node == NULL )
{
printf("Fatal: This index is invalid. Try another.\n\n");
return;
}

fflush(stdin);
printf("\n- Input good's name:\n> ");
gets( node->Name );

printf("\n- Input good's country:\n> ");


gets( node->Country );

printf("\n- Input good's manufacturer:\n> ");


gets( node->Manufacturer );

fflush(stdin);
printf("\n- Input good's vendor code:\n> ");
scanf("%d", &node->Vendorcode );

printf("\n- Input good's price:\n> ");


scanf("%d", &node->Price );

printf("\nElement #%d edited succesfully.", i);


}

void RemoveElement( Node *&head )


{
printf("\n ----- 8. Removing an element -----\n\n");

printf("\nInput the index of the element to remove:\n> ");


int i;
scanf("%d", &i);

Node *node = GetNthNodeFromHead(head, i);


if( node == NULL )
{
printf("Fatal: This index is invalid. Try another.\n\n");
return;
}

if( head == node )


{
head = node->Next;

12
}
else
{
Node *temp = head;
do
{
if( temp->Next == node )
{
temp->Next = node->Next;
break;
}
temp = temp->Next;

} while ( temp->Next );
}

free(node);
}

void FreeAllElements( Node *&head )


{
printf("\n ----- 9. Free Memory -----\n\n");
printf(" Memory freed.\n");
FreeMemory(head);
}

void SaveToFile( Node *&head )


{
printf("\n ----- 10. Save to file -----\n\n");

FILE *fp;
fp = fopen("goods.txt", "w");

int count = 0;
Node *temp = head;
while(temp)
{
count++;
temp = temp->Next;
}

fprintf(fp, "%d\n", count);


temp = head;

while(temp)
{
13
fprintf(fp, "%s\n", temp->Name);
fprintf(fp, "%s\n", temp->Country);
fprintf(fp, "%s\n", temp->Manufacturer);
fprintf(fp, "%d\n", temp->Vendorcode);
fprintf(fp, "%d\n", temp->Price);

temp = temp->Next;
}

fclose (fp);
printf("\nFile saved succesfully.");
}

void ReadFromFile( Node *&head )


{
printf("\n ----- 10. Save to file -----\n\n");

FILE *fp;
fp = fopen("goods.txt", "r");

int count = 0;
fscanf(fp, "%d\n", &count);

if(count < 1)
return;

FreeMemory( head );
head = new Node;

Node *temp = head;


for ( int i = 0; i < count; i++ )
{
fgets(temp->Name, sizeof(temp->Name), fp);
fgets(temp->Country, sizeof(temp->Country), fp);
fgets(temp->Manufacturer, sizeof(temp->Manufacturer), fp);
fscanf(fp, "%d\n", &temp->Vendorcode);
fscanf(fp, "%d\n", &temp->Price);

// fix newline at strings


temp->Name[strlen(temp->Name) - 1] = '\0';
temp->Country[strlen(temp->Country) - 1] = '\0';
temp->Manufacturer[strlen(temp->Manufacturer) - 1] = '\0';

if(i < (count - 1))


{
14
temp->Next = new Node;
temp = temp->Next;
}
}

fclose (fp);
printf("\nFile read succesfully.");
}

void SplitList( Node *&head, Node *&head2 )


{
printf("\nInput the index of the element to be the start of the split list:\n> ");
int i;
scanf("%d", &i);

Node *node = GetNthNodeFromHead(head, i);


if( node == NULL )
{
printf("Fatal: This index is invalid. Try another.\n\n");
return;
}

head2 = node;

Node *tempA = head;


while(tempA != NULL && tempA->Next != head2) tempA = tempA->Next;

tempA->Next = NULL;
}

void MergeList( Node *&head, Node *&head2 )


{
Node *lastA = head;
while(lastA->Next != NULL) lastA = lastA->Next;

Node *lastB = head2;


while(lastB->Next != NULL) lastB = lastB->Next;

lastA->Next = head2;
head2 = NULL;
}

void ShowAddress( Node *head )


{
printf("\n ----- 14. Show addresses -----\n\n");

15
int i = 0;

Node *node = head;


while(node != NULL)
{
printf("%d: %p\n", i, node);
node = node->Next;
i++;
}
}

void ShowCount( Node *head )


{
printf("\n ----- 15. Show count -----\n\n");
int i = 0;

Node *node = head;


while(node != NULL)
{
i++;
node = node->Next;
}

printf("Count: %d elements.\n", i );
}

void Swap( Node *&head, Node *node1, Node *node2 )


{
// Either of the elements do not exist.
if( !node1 || !node2 )
return;

// We are switching the same element.


if(node1 == node2)
return;

Node *parent1 = NULL, *parent2 = NULL;


Node *temp = head;

// finding parents for nodes


while(temp)
{
Node *next = temp->Next;
if(next == node1) parent1 = temp;
if(next == node2) parent2 = temp;

16
temp = next;
}

if (node1->Next == node2)
{
node1->Next = node2->Next;
node2->Next = node1;
if(parent1) parent1->Next = node2;
}
else if (node2->Next == node1)
{
node2->Next = node1->Next;
node1->Next = node2;
if(parent2) parent2->Next = node1;
}
else
{
Node *temp = node1->Next;
node1->Next = node2->Next;
node2->Next = temp;
if(parent1) parent1->Next = node2;
if(parent2) parent2->Next = node1;
}

// changing the head


if(head == node1) head = node2;
else if(head == node2) head = node1;
}
Node *CreateNode()
{
Node *node = new Node;

fflush(stdin);
printf("\n- Input good's name:\n> ");
gets( node->Name );

printf("\n- Input good's country:\n> ");


gets( node->Country );

printf("\n- Input good's manufacturer:\n> ");


gets( node->Manufacturer );

fflush(stdin);
printf("\n- Input goos's vendor code:\n> ");

17
scanf("%d", &node->Vendorcode );

printf("\n- Input good's price:\n> ");


scanf("%d", &node->Price );

return node;
}

Node *GetLastNodeFromHead( Node *head )


{
if( head == NULL )
return NULL;

Node *node = head;


int i = 0;

while(node->Next != NULL)
{
i++;
node = node->Next;
}

return node;
}

Node *GetNthNodeFromHead( Node *head, int n )


{
if( head == NULL )
return NULL;

Node *node = head;

for(int i = 0; i < n; i++)


{
node = node->Next;

// if we reached the end, break the loop and return null.


if(node == NULL)
break;
}

return node;
}

int GetIndexOfNodeFromHead( Node *head, Node *node )


18
{
if( !head || !node )
return -1;

int i = 0;
Node *temp = head;

do
{
if(temp == node)
return i;

temp = temp->Next;
i++;

} while (temp != NULL);

return -1;
}
void FreeMemory( Node *&head )
{
if(head == NULL)
return;

Node *node = head;


do
{
Node *temp = node;
node = node->Next;
free(temp);

} while ( node );

head = NULL;
}
Пример работы программы:

19
20
21
22
23
24
25
Вывод:
В ходе лабораторной работы номер 8-9 “ Изучение возможностей и средств языка Си для
реализации и использования основных операций обработки односвязного списка.” Я
познакомилась с понятием односвязный список и обучилась с ним взаимодействовать. Научилась
создавать односвязные и производить различные операции с ними. Свою программу я создавала
посредством проекта из 3 файлов(основного, заголовочного и файла с реализацией функций).

26

Вам также может понравиться