Traverse a singly linked list from the beginning to the end and reverse all the increasing and decreasing sequence of components present in the list. Component is the collection of continuous elements either in increasing or decreasing order. Example: Let the list contains 1, 2, 3, 7, 4, 2, 9, 7, 8 elements. Here the components are “1, 2, 3, 7”, “4, 2”, “9, 7”, and “8”. The code should produce the list with elements 7, 3, 2, 1, 2, 4, 7, 9, 8.
//Very version
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
#define MXSIZE 6555
typedef struct List
{
int d;
struct List* pNext;
}List;
void push(List** hd, const int s)
{
if ((*hd) == NULL)
{
(*hd) = (List*)malloc(sizeof(List));
(*hd)->pNext = NULL;
(*hd)->d = s;
}
else
{
List* p = (*hd);
while (p->pNext)
{
p = p->pNext;
}
List* nw = (List*)malloc(sizeof(List));
nw->pNext = NULL;
nw->d = s;
p->pNext = nw;
}
}
void Print(List* h)
{
List* p = h;
while (p)
{
int cur;
cur = p->d;
printf("%i\n", cur);
p = p->pNext;
}
}
void clear(List** h)
{
List* pr = NULL;
while ((*h)->pNext)
{
pr = (*h);
(*h) = (*h)->pNext;
free(pr);
}
free((*h));
}
int* toArray(List* hd, int* size)
{
int* mas = (int*)malloc(sizeof(int) * MXSIZE);
*size = 0;
List* p = hd;
while (p)
{
mas[(*size)] = p->d;
p = p->pNext;
*size = *size + 1;
}
return mas;
}
int main()
{
int n;
printf("Enter size:=");
scanf("%i", &n);
printf("Enter elements\n");
List* hd = NULL;
for (int i = 0; i < n; i++)
{
int x;
scanf("%i", &x);
push(&hd, x);
}
int siz = 0;
int* ms = toArray(hd, &siz);
int cnt = 0;
for (int i = 0; i < siz-1; i++)
{
if (ms[i] < ms[i + 1])
{
int j = i;
while (i < siz - 1 && ms[i] < ms[i + 1])
{
i++;
}
int d = i;
while (d >= j)
{
printf("%i ", ms[d--]);
cnt++;
}
}
else if (ms[i] > ms[i + 1])
{
int j = i;
while (i < siz - 1 && ms[i] > ms[i + 1])
{
i++;
}
int d = i;
while (d >= j)
{
printf("%i ", ms[d--]);
cnt++;
}
}
else {
printf("%i ", ms[i]);
cnt++;
}
}
if (cnt != siz)
printf("%i", ms[siz - 1]);
free(ms);
return 0;
}
Comments
Leave a comment