Advertisement
mierzvoj

Untitled

Apr 8th, 2022
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.98 KB | None | 0 0
  1.  
  2. #include <stdio.h>
  3. struct Node {
  4. int data;
  5. struct Node *next;
  6. struct Node *prev;
  7. };
  8. struct Node *head;
  9. struct Node* GetNewNode(int x){
  10.  
  11. struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
  12. newNode->data=x;
  13. newNode->prev=NULL;
  14. newNode->next=NULL;
  15. return newNode;
  16. }
  17. void InsertAtHead(int x){
  18.  
  19. struct Node *newNode = GetNewNode(x);
  20. if(head == NULL){
  21. head = newNode;
  22. return;
  23. }
  24. head->prev = newNode;
  25. newNode->next = head;
  26. head = newNode;
  27.  
  28. }
  29.  
  30. void insertAtTail(int x){
  31. struct Node* last = head;
  32. struct Node *newNode = GetNewNode(x);
  33. if(head == NULL){
  34. head = newNode;
  35. return;
  36. }
  37. newNode->next = NULL;
  38. while(last->next != NULL){
  39. last = last->next;
  40. }
  41. last->next=newNode;
  42. newNode->prev=last;
  43.  
  44.  
  45. }
  46. void insertAfter(int loc, int x){
  47. struct Node *temp=head;
  48.  
  49. for(int i=0;i<loc;i++){
  50. temp = temp->next;
  51. }
  52.  
  53. struct Node* prevNode = temp;
  54.  
  55. struct Node *newNode = GetNewNode(x);
  56. newNode->next = prevNode->next;
  57. prevNode->next=newNode;
  58. newNode->prev=prevNode;
  59. if (newNode->next != NULL){
  60. newNode->next->prev = newNode;
  61. }
  62. printf("%d", *(newNode->prev));
  63. }
  64.  
  65. void Print(){
  66. struct Node *temp = head;
  67. while(temp != NULL){
  68. printf("%d ", temp->data);
  69. temp = temp->next;
  70. }
  71. }
  72. void RevPrint(){
  73. struct Node *temp = head;
  74. while(temp->next != NULL){
  75. temp = temp->next;
  76. }
  77. while(temp != NULL){
  78. printf("%d ", temp->data);
  79. temp = temp->prev;
  80. }
  81. }
  82.  
  83.  
  84. int main()
  85. {
  86. head = NULL;
  87. InsertAtHead(2); Print(); RevPrint();
  88. printf("\n");
  89. InsertAtHead(4); Print(); RevPrint();
  90. printf("\n");
  91. InsertAtHead(6); Print(); RevPrint();
  92. printf("\n");
  93. insertAtTail(5); Print(); RevPrint();
  94. printf("\n");
  95. insertAfter(1, 55 ); Print(); RevPrint();
  96. }
  97.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement