You are given a list, L, and another list, P, containing integers sorted in ascending order. The operation printLots(L,P)
will print the elements in L that are in positions specified by P. For instance, if P = 1, 3, 4, 6
, the elements in positions 1, 3, 4, and 6
in L are printed. Write the procedure printLots(L,P)
. You may use only the public STL
container operations. What is the running time of your procedure?
This is what I have so far. Everything compiles, however after running it and using option 3, nothing is printed and I'm not sure what I've done wrong.
At first I was trying to make it with multiple options to where you could add elements, etc., but if someone could please just help me with the basic aspects of the question or help me fix what I have, that would be greatly appreciated.
#include <iostream>
#include <stdlib.h>
#include <cstdio>
#define NULL 0
using namespace std;
struct node
{
int elements;
struct node *link;
};
typedef struct node NODE;
NODE* create(NODE* h, int P);
int count(NODE* h);
NODE* sort(NODE* h);
void printLots(NODE* L, NODE* P);
NODE* create(NODE* h, int P)
{
if (h == NULL)
{
h = (NODE*)malloc(sizeof(NODE));
h->elements = P;
h->link = NULL;
}
else
{
h->link = create(h->link, P);
}
return (h);
printf("h");
}
int count(NODE* h)
{
int count = 0;
if (h != NULL)
{
count++;
h = h->link;
}
return count;
}
NODE* sort(NODE* h)
{
int i, q, r, temp;
NODE* htemp = h;
i = count(h);
for (q = 0; q < i; q++)
{
for (r = 0; r < i - 1; r++)
{
if (h->elements > h->link->elements)
{
temp = h->elements;
h->elements = h->link->elements;
h->link->elements = temp;
}
h = h->link;
}
h = htemp;
}
return htemp;
}
void printLots(NODE* L, NODE* P)
{
int countL, countP, i, j;
NODE* temp = L;
P = sort(P);
L = sort(L);
countL = count(L);
countP = count(P);
for (i = 0; i < countP; i++)
{
if (P->elements > countL)
{
printf("The L list does not contain %d elements\n", P->elements);
}
else
{
for (j = 0; j < P->elements - 1; j++)
{
L = L->link;
printf("%d\n", L->elements);
L = temp;
}
}
P = P->link;
}
}
int main()
{
int cs, value;
NODE *L, *P;
L = NULL;
P = NULL;
while (1)
{
printf("1.Add to list L\n");
printf("2.Add to list P\n");
printf("3.Print List\n");
printf("4.Clear Screen\n");
printf("5.Exit\n");
printf("Enter your choice: ");
scanf_s("%d", &cs);
switch (cs)
{
case 1: scanf_s("%d", &value);
L = create(L, value);
break;
case 2: scanf_s("%d", &value);
P = create(P, value);
break;
case 3: printLots(L, P);
break;
case 4: system("cls");
break;
case 5: exit(1);
break;
}
}
}