bhupixb

linked list adding an element

Oct 23rd, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.59 KB | None | 0 0
  1. #include <stdio.h>
  2. #include "stdlib.h"
  3. typedef struct st{
  4. int data;
  5. struct st *next;
  6. }node;
  7.  
  8. node* new_node(){
  9. return (node *) malloc(sizeof(node));
  10. }
  11.  
  12. void add(int num, int ch, node **head, node **start){
  13. node* temp = new_node();
  14. temp->data = num;
  15. // At the end
  16. if(!ch){
  17. temp->next = NULL;
  18. temp->data = num;
  19. // printf("%d ", temp->data);
  20. (*head)->next = temp;
  21. //printf("%d \n", (*head)->next);
  22. *head = temp;
  23. //printf("%d \n", *head);
  24. return;
  25. }
  26. //Front
  27. temp->next = *start;
  28. *start = temp;
  29. }
  30. void display(node *head){
  31. if(head == NULL)
  32. return;
  33. if(head->data != -1)
  34. printf("%d ", head->data);
  35. display(head->next);
  36. }
  37. // Only deletes from Front
  38. void delete_node(node **start){
  39. node* temp = *start;
  40. *start = temp->next;
  41. }
  42. int main(){
  43. node *head = new_node(), *start, *temp;// = new_node();Still works
  44. head->next = NULL;
  45. head->data = -1;
  46. start = head;
  47. // printf("%d\n", start->data);
  48. int n, num, ch;
  49. scanf("%d", &n);
  50.  
  51. while(n--){
  52. scanf("%d %d", &ch, &num);
  53. //scanf("%d", &num);
  54. add(num, ch, &head, &start);
  55. // display(temp = start);
  56. printf("\n");
  57. }
  58. delete_node(&start);
  59. display(temp = start);
  60. // printf("%d", head->next);
  61. /* head = start;
  62. while(head != NULL){
  63. if(head->data != -1)
  64. printf("%d ", head->data);
  65. head = head->next;
  66. // display(start , head);
  67. }*/
  68. return 0;
  69. }
Add Comment
Please, Sign In to add comment