Task: Given a sequence of real numbers a1, a2, ..., an (n> = 2 and unknown in advance). If the sequence is ordered not to decrease, then leave it unchanged, otherwise get the sequence an, a (n-1), ...., a1.

I was given only linear lists and a function fopen (fopen_s) at the university. I read all the top articles from Google, I figured it out in lists, but I don’t understand how to solve this problem using lists. Please help me with an idea or with examples of solutions for similar problems.

1 answer 1

to expand a single-linked list, you need to make the next point to the previous and the previous to the next, while the new head becomes the tail and vice versa - everything is simple

Wrote in C ++, the translation in C will be your add. trivial assignment

/* o1->o2->o3->o4 o4->o3->o2->o1 // после реверса */ #include <iostream> using namespace std; struct node { int data; node* next; }; void reverse(node*& head) { if (head == nullptr || head->next == nullptr) return; node* prev = nullptr; node* next = nullptr; while (head) { next = head->next; head->next = prev; prev = head; head = next; } head = prev; } void printList(node* head) { node* tmp = head; while (tmp) { cout << tmp->data << ' '; tmp = tmp->next; } cout << endl; } int main(int argc, char** argv) { node a, b, c, d; a.data = 1; a.next = &b; b.data = 2; b.next = &c; c.data = 3; c.next = &d; d.data = 4; d.next = nullptr; node* head = &a; printList(head); reverse(head); printList(head); } 
  • Thanks, translated to C. But the program still does not work. - Alexander
  • @ Alexander, well, it means that they were translated incorrectly, which means it does not work ?? - ampawd
  • I wanted to throw the code, but something happened to VS. Wait 10 minutes please. - Alexander
  • I understood my mistake, for some reason I thought that cout is just an analogue of printf in C ++. How to correctly transfer the while loop from the printList function? - Alexander
  • @ Alexander and what is there to translate? while while loop and C is the same - ampawd