fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. #define SUCCESS 0
  5. #define FAIL -1
  6. #define TRUE 0
  7. #define FALSE -1
  8. #define ALLOCFAIL -2
  9. #define EMPTY -3
  10.  
  11.  
  12. typedef struct Node{
  13. struct Node* next;
  14. struct Node* prev;
  15. int data;
  16. } node;
  17.  
  18. int push(node **head, int datainput){
  19. /* Initialization of new node */
  20. node* newptr = (node*) malloc(sizeof(node));
  21. if(newptr == NULL){
  22. return ALLOCFAIL;
  23. }
  24. newptr->next = NULL;
  25. newptr->data = datainput;
  26.  
  27. /* Check for empty list */
  28. if(*head == NULL){
  29. newptr->prev = NULL;
  30. *head = newptr; // change where head is pointing to
  31. return SUCCESS;
  32. }
  33.  
  34. /* Get to the end of list*/
  35. node* headptr = *head;
  36. while(headptr->next != NULL){
  37. headptr = headptr->next;
  38. }
  39.  
  40. headptr->next = newptr;
  41. newptr->prev = headptr;
  42. return SUCCESS;
  43. }
  44.  
  45. int printlist(node* head){
  46. /* Check if valid node or empty list */
  47. if(head == NULL){
  48. return EMPTY;
  49. }
  50.  
  51. /* Move to first node if not already */
  52. node* firstptr = head;
  53. while(firstptr->prev != NULL){
  54. firstptr = firstptr->prev;
  55. }
  56.  
  57. /* Print entire list*/
  58. while(firstptr != NULL){
  59. if(firstptr->next != NULL){
  60. printf("%d -> ", firstptr->data);
  61. }
  62. else{
  63. printf("%d", firstptr->data);
  64. }
  65. firstptr = firstptr->next;
  66. }
  67.  
  68. puts("");
  69.  
  70. return SUCCESS;
  71. }
  72.  
  73.  
  74. int main(void)
  75. {
  76. node *head = NULL; // <-- important initialization
  77.  
  78. push(&head, 10);
  79. push(&head, 20);
  80. push(&head, 30);
  81. push(&head, 40);
  82.  
  83. printlist(head);
  84.  
  85. return 0;
  86. }
  87.  
  88.  
Success #stdin #stdout 0s 4428KB
stdin
Standard input is empty
stdout
10 -> 20 -> 30 -> 40