Advertisement
Guest User

find_max

a guest
Feb 21st, 2020
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.54 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. typedef struct Node
  4. {
  5.     int data;
  6.     struct Node *next;
  7. } Node;
  8.  
  9. // create new node
  10. Node *makeNode(int key)
  11. {
  12.     Node *newNode = (Node *)malloc(sizeof(Node));
  13.     if (!newNode)
  14.         return NULL;
  15.     newNode->data = key;
  16.     newNode->next = NULL;
  17.     return newNode;
  18. }
  19.  
  20. // adds a new node item to the end of the list
  21. Node *add_last(Node *head, Node *newItem)
  22. {
  23.     Node *currItem;
  24.     if (!head)
  25.         return newItem;
  26.     currItem = head;
  27.     while (currItem->next)
  28.         currItem = currItem->next;
  29.     currItem->next = newItem;
  30.     return head;
  31. }
  32.  
  33. int help(Node *head, int data, int flag)
  34. {
  35.     if (!head)
  36.         return 1;
  37.  
  38.     if (data >= head->data)
  39.         flag = help(head->next, data, flag);
  40.     else
  41.         return 0;
  42.     return flag;
  43. }
  44. // (2)->(7)->(1)->(3)->(6)
  45.  
  46. Node *delMax(Node *head)
  47. {
  48.     if (!head->next)
  49.         return;
  50.     if (help(head->next, head->data, 0))
  51.         return head->next;
  52.  
  53.     if (help(head, head->next->data, 0))
  54.     {
  55.         head->next = head->next->next;
  56.         return;
  57.     }
  58.     delMax(head->next);
  59.     return head;
  60. }
  61.  
  62. void main()
  63. {
  64.     Node *res;
  65.     Node *head;
  66.     head = makeNode(2); // (2)->(7)->(1)->(3)->(6)
  67.     head = add_last(head, makeNode(7));
  68.     head = add_last(head, makeNode(1));
  69.     head = add_last(head, makeNode(3));
  70.     head = add_last(head, makeNode(6));
  71.     res = delMax(head);
  72.  
  73.     Node *current = res;
  74.     while (current)
  75.     {
  76.         printf("%d ", current->data);
  77.         current = current->next;
  78.     }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement