Advertisement
Guest User

Untitled

a guest
Apr 26th, 2017
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.83 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <malloc.h>
  3.  
  4. typedef struct node {
  5.  
  6. int data;
  7. struct node* next,
  8. * prev;
  9. } Node;
  10.  
  11. void push(Node**head, int data) {
  12.  
  13. //dynamic allocation for a new node
  14. Node *temp = (Node*)malloc(sizeof(Node));
  15.  
  16. //put in data
  17. temp->data = data;
  18.  
  19. //update next area
  20. temp->next = (*head);
  21.  
  22. //update prev area
  23. temp->prev = NULL;
  24.  
  25. if((*head) != NULL) (*head)->prev = temp;
  26.  
  27. //move the head here
  28. (*head) = temp;
  29. };
  30.  
  31. void print(Node *head) {
  32.  
  33. while(head != NULL) {
  34.  
  35. printf("%d ", head->data);
  36.  
  37. head = head->next;
  38. }
  39. printf("\n");
  40. };
  41.  
  42.  
  43. void printR(Node *head) {
  44.  
  45. Node*last;
  46.  
  47. while(head != NULL) {
  48.  
  49. last = head;
  50.  
  51. head = head->next;
  52. }
  53.  
  54. while(last != NULL) {
  55.  
  56. printf("%d ",last->data);
  57.  
  58. last = last->prev;
  59. }
  60.  
  61. };
  62.  
  63. void addNode(Node **head, int pos, int data) {
  64.  
  65. Node *new_node = (Node*)malloc(sizeof(Node));
  66. new_node->data = data;
  67.  
  68. int k = 0;
  69. Node *aux = (*head);
  70.  
  71. while(k++ < pos) {
  72. aux = aux->next;
  73. }
  74.  
  75. if(aux->next == NULL) {
  76. aux->next = new_node;
  77. new_node->next = NULL;
  78. new_node->prev = aux;
  79. return;
  80. }
  81.  
  82. new_node->next = aux->next;
  83. aux->next->prev = new_node;
  84. aux->next = new_node;
  85. new_node->prev = aux;
  86.  
  87.  
  88. };
  89.  
  90. int main() {
  91.  
  92. Node *head = NULL;
  93. push(&head,1);
  94. push(&head,2);
  95. push(&head,3);
  96. push(&head,4);
  97. push(&head,5);
  98. push(&head,6);
  99. push(&head,7);
  100. print(head);
  101. addNode(&head,5,171);
  102. print(head);
  103.  
  104. return(0);
  105. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement