Advertisement
Sierra_ONE

Stack Sorted (LL & Arr)

Sep 23rd, 2024
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.24 KB | Source Code | 0 0
  1. void sortStack(Stack *A) {
  2.     Stack temp = initStack();
  3.     char curr;
  4.  
  5.     while (!isEmpty(*A)) {
  6.         // Remove the top element from the original stack
  7.         curr = topElem(*A);
  8.         Pop(A);
  9.  
  10.         // Transfer elements from temp back to the original stack if they are larger than the current element
  11.         while (!isEmpty(temp) && topElem(temp) > curr) {
  12.             Push(A, topElem(temp));
  13.             Pop(&temp);
  14.         }
  15.  
  16.         // Push the current element into the temp stack
  17.         Push(&temp, curr);
  18.     }
  19.  
  20.     // Transfer sorted elements back to the original stack
  21.     while (!isEmpty(temp)) {
  22.         Push(A, topElem(temp));
  23.         Pop(&temp);
  24.     }
  25. }
  26.  
  27.  
  28. // Insert Sorted:
  29. void insertSorted(Stack *A, char elem) {
  30.     Stack temp = initStack();
  31.    
  32.     // Transfer elements from original stack to temp until we find the correct position for elem
  33.     while (!isEmpty(*A) && topElem(*A) > elem) {
  34.         Push(&temp, topElem(*A));
  35.         Pop(A);
  36.     }
  37.    
  38.     // Insert the new element at the correct position
  39.     Push(A, elem);
  40.    
  41.     // Move the rest of the elements back from temp to the original stack
  42.     while (!isEmpty(temp)) {
  43.         Push(A, topElem(temp));
  44.         Pop(&temp);
  45.     }
  46. }
  47.  
  48.  
Tags: dsa
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement