Advertisement
Adrita

double linked list

Jul 25th, 2019
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.94 KB | None | 0 0
  1. #include<stdio.h>
  2. struct linked_list
  3. {
  4. int data;
  5. struct linked_list *next;
  6. };
  7. typedef struct linked_list *node;
  8.  
  9. node createnode()
  10. {
  11. node temp;
  12. temp=(node)malloc(sizeof(node));
  13. temp->next=NULL;
  14. return temp;
  15. }
  16. node add_node(node head,int value)
  17. {
  18. node temp=createnode(),p;
  19. temp->data=value;
  20. if(head==NULL)
  21. head=temp;
  22. else
  23. {
  24. p=head;
  25. while(p->next!=NULL)
  26. p=p->next;
  27. p->next=temp;
  28. }
  29. return head;
  30. }
  31. node add_node_front(node head,int value)
  32. {
  33. node p=createnode();
  34.  
  35. p->data=value;
  36. p->next=head;
  37. head=p;
  38.  
  39. return head;
  40. }
  41. void print_node(node head)
  42. {
  43. node a;
  44. if(head==NULL)
  45. printf("empty\n");
  46. else
  47. {
  48. a=head;
  49. while(a!=NULL)
  50. {
  51. printf("%d ",a->data);
  52. a=a->next;
  53. }
  54. }
  55. printf("\n");
  56. }
  57. node print_node_rev(node head)
  58. {
  59. node prev,next,current;
  60. current=head;
  61. prev=NULL;
  62. while(current!=NULL)
  63. {
  64. next=current->next;
  65. current->next=prev;
  66. prev=current;
  67. current=next;
  68. }
  69. head=prev;
  70. return head;
  71. }
  72.  
  73. int main()
  74. {
  75. printf("enter 1 to add node at thge end\nenter 2 to add node at the front\nenter 3 to print\nenter 4 to print rev\n");
  76. int n;
  77. node head;
  78. head=NULL;
  79. x:
  80. scanf("%d",&n);
  81. if(n==1)
  82. {
  83. int ndata;
  84. printf("new data\n");
  85. scanf("%d",&ndata);
  86. head=add_node(head,ndata);
  87. goto x;
  88. }
  89. else if(n==3)
  90. {
  91. print_node(head);
  92. goto x;
  93. }
  94. else if(n==2)
  95. {
  96.  
  97. int mdata;
  98. printf("new data\n");
  99. scanf("%d",&mdata);
  100. head=add_node_front(head,mdata);
  101. goto x;
  102. }
  103. else if(n==4)
  104. {
  105. head=print_node_rev(head);
  106. print_node(head);
  107. goto x;
  108. }
  109. else if(n==0)
  110. return 0;
  111. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement