fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. struct DoublyLinkedListNode {
  5. int data;
  6. DoublyLinkedListNode* next;
  7. DoublyLinkedListNode* prev;
  8.  
  9. DoublyLinkedListNode(int val) {
  10. data = val;
  11. next = nullptr;
  12. prev = nullptr;
  13. }
  14. };
  15.  
  16. DoublyLinkedListNode* sortedInsert(DoublyLinkedListNode* head, int data) {
  17. DoublyLinkedListNode* newNode = new DoublyLinkedListNode(data);
  18.  
  19. if (!head || data < head->data) {
  20. newNode->next = head;
  21. if (head) head->prev = newNode;
  22. return newNode;
  23. }
  24.  
  25. DoublyLinkedListNode* current = head;
  26. while (current->next && current->next->data < data) {
  27. current = current->next;
  28. }
  29.  
  30. newNode->next = current->next;
  31. if (current->next) current->next->prev = newNode;
  32. current->next = newNode;
  33. newNode->prev = current;
  34.  
  35. return head;
  36. }
  37.  
  38. void printList(DoublyLinkedListNode* head) {
  39. while (head) {
  40. cout << head->data << " ";
  41. head = head->next;
  42. }
  43. cout << endl;
  44. }
  45.  
  46. int main() {
  47. DoublyLinkedListNode* head = nullptr;
  48.  
  49. head = sortedInsert(head, 10);
  50. head = sortedInsert(head, 30);
  51. head = sortedInsert(head, 20);
  52. head = sortedInsert(head, 5);
  53.  
  54. printList(head);
  55.  
  56. return 0;
  57. }
  58.  
Success #stdin #stdout 0.01s 5320KB
stdin
Standard input is empty
stdout
5 10 20 30