Как разделить список на 2 равных списка?
Я создал односвязный линейный список:
#define _CRT_SECURE_NO_WARNINGS
#include<Windows.h>
#include <stdio.h>
#include <stdlib.h>
#define N 2
#define top_range 100
#define M 100
typedef struct node
{
char firm[M];
char type[M];
char color[M];
int price;
struct node *next;
}node;
void new_node( node **head, node **last)
{
node *current;
if ((current = (struct node *)malloc(sizeof(struct node))) == NULL)
{
fprintf(stderr,"No free memory");
exit(EXIT_FAILURE);
}
else
{
current->next = NULL;
current->price = rand() % top_range;
printf("Firm:");
scanf("%s",current->firm);
printf("Color:");
scanf("%s", current->color);
printf("Type:");
scanf("%s", current->type);
printf("\n");
if (!(*head))
*head = current;
else
(*last)->next = current;
*last = current;
}
}
void print_out( node *lst)
{
{
while (lst)
{
printf("Price:%5d\nFirm:%5s\nColor:%5s\nType:%5s\n", lst->price, lst->firm, lst->color, lst->type);
printf("\n");
lst = lst->next;
}
}
printf("\n");
}
int main()
{
struct node *head = NULL;
struct node *last = NULL;
struct node *new_head = NULL;
int i, pos;
for (i = 0; i < N;i++)
new_node(&head, &last);
printf("List - \n");
print_out(head);
getchar();
getchar();
return 0;
}
Как разделить этот список на 2 равных списка и вывести их?
Ответы (1 шт):
Автор решения: AlexGlebe
→ Ссылка
Я разделил списки на равные по длине. Если не то, то скажите.
node * half_list ( node * const head ) {
node * j = head ;
// элемент перед половиной списка
node * prev = NULL ;
// половина списка
node * half = j ;
// цикл списка по два элемента
// а половину по одному
while ( j ) {
if ( j -> next )
j = j -> next ;
else
break ;
prev = half ;
half = half -> next ;
j = j -> next ; }
// отрезаем у первого списка конец
if ( prev )
prev -> next = NULL ;
// возвращаем остаток
return half ; }
...
printf("1.List - \n");
print_out(head);
new_head = half_list ( head ) ;
printf("2.List - \n");
print_out(head);
printf("3.List - \n");
print_out(new_head);