-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathswap.c
50 lines (44 loc) · 1.14 KB
/
swap.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "main.h"
#define MAX_LINE_LENGTH 256
/**
* swap - Swaps the top two elements of the stack.
*
* @stack: A pointer to the stack.
* @lineNumber: The line number in the file where the operation occurred.
*
* Description:
* This function swaps the top two elements of the stack. If the stack
* is too short (less than two elements), it prints an error message and
* exits with a failure status.
*
* Parameters:
* - stack: A pointer to the stack.
* - lineNumber: The line number in the file where the operation occurred.
*
* Example:
* swap(&stack, 5);
* // Swaps the top two elements of the stack.
*/
void swap(stack_t **stack, unsigned int lineNumber)
{
stack_t *first;
stack_t *second;
if (*stack == NULL || (*stack)->next == NULL)
{
fprintf(stderr, "L%u: can't swap, stack too short\n", lineNumber);
exit(EXIT_FAILURE);
}
first = *stack;
second = first->next;
first->next = second->next;
if (second->next != NULL)
second->next->prev = first;
second->prev = NULL;
second->next = first;
first->prev = second;
*stack = second;
}