Answer the question
In order to leave comments, you need to log in
How to swap stack/singly linked list nodes?
I want to swap the stack nodes containing the minimum and maximum elements.
In my algorithm, when min. and max. are nearby, a loop occurs (the node points to itself).
#include <stdio.h>
struct Stack {
int value;
struct Stack *next;
};
void print_stack(struct Stack *head)
{
struct Stack *h = head;
if (h == NULL) return;
while (h != NULL)
{
printf("%d at %p\n", h->value, h);
h = h->next;
}
}
struct Stack *swap_min_max_nodes(struct Stack *head)
{
struct Stack *h = head;
if (h == NULL) return head;
struct Stack *min = h, *max = h;
struct Stack *before_min = NULL, *before_max = NULL;
while (h != NULL)
{
if (h->value < min->value) {before_min = min; min = h;}
if (h->value > max->value) {before_max = max; max = h;}
h = h->next;
}
if (before_min) before_min->next = max;
if (before_max) before_max->next = min;
struct Stack *tmp = min->next;
min->next = max->next;
max->next = tmp;
struct Stack *new_head = head;
if (new_head == min) new_head = max;
if (new_head == max) new_head = min;
return new_head;
}
int main(void)
{
//struct Stack a = {1,NULL};
//struct Stack b = {2,&a};
//struct Stack head = {3,&b};
struct Stack a = {3,NULL};
struct Stack b = {1,&a};
struct Stack c = {4,&b};
struct Stack head = {2,&c};
print_stack(&head);
struct Stack *new_head = swap_min_max_nodes(&head);
printf("\n");
print_stack(new_head);
return 0;
}
Answer the question
In order to leave comments, you need to log in
Well, yes, you will have to consider a separate case - when they are in a row. Check that and suddenly min->next == max
. Draw a picture of four points before_min, min, max, max->next with arrows before and after the change. Look at which three vertices the links will change and how. Write it down in code.
There is another case max->next == min
, but it can be considered together with the previous one - just in this case, swap the min and max pointers (as well as before_min and before_max). Then the code for the previous case will work. At the time of the change, it doesn’t matter to you which peak is the maximum and which is the minimum. You only need to swap 2 given vertices.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question