fork download
  1. #include <iostream>
  2. #include <string>
  3.  
  4. using namespace std;
  5.  
  6. struct ListNode {
  7. int val;
  8. ListNode* prev;
  9. ListNode* next;
  10. ListNode(int x) : val(x), prev(nullptr), next(nullptr) {}
  11. };
  12.  
  13. // Function to Insert a new node at the tail of the list
  14. void insertAtTail(ListNode*& head, int val) {
  15. ListNode* newNode = new ListNode(val);
  16. if (head == nullptr) {
  17. head = newNode;
  18. } else {
  19. ListNode* temp = head;
  20. while (temp->next != nullptr) {
  21. temp = temp->next;
  22. }
  23. temp->next = newNode;
  24. newNode->prev = temp;
  25. }
  26. }
  27.  
  28. // Serialization
  29. string serialize(ListNode* head) {
  30. string serializedData;
  31. ListNode* curr = head;
  32. while (curr != nullptr) {
  33. serializedData += to_string(curr->val) + ",";
  34. curr = curr->next;
  35. }
  36. return serializedData;
  37. }
  38.  
  39. // Deserialization
  40. ListNode* deserialize(string data) {
  41. ListNode* head = nullptr;
  42. string numStr = "";
  43. int dataSize = data.size();
  44. int i = 0;
  45. while (i < dataSize) {
  46. numStr = "";
  47. while (i < dataSize && data[i] != ',') {
  48. numStr += data[i];
  49. i++;
  50. }
  51. if (i < dataSize) {
  52. i++;
  53. }
  54. int val = stoi(numStr);
  55. insertAtTail(head, val);
  56. }
  57. return head;
  58. }
  59.  
  60. // Printing the doubly linked list
  61. void printList(ListNode* head) {
  62. ListNode* curr = head;
  63. while (curr != nullptr) {
  64. cout << curr->val << " ";
  65. curr = curr->next;
  66. }
  67. cout << endl;
  68. }
  69.  
  70. int main() {
  71. string str="1,20,35,4,51,82,90,100";
  72. ListNode* head = deserialize(str);
  73. cout<<"String to deserialise: "<<str<<endl;
  74. cout << "Deserialized list: ";
  75. printList(head);
  76. cout<<"Serialising the same deserialised list.... "<<endl;
  77. string serializedData = serialize(head);
  78. cout << "Serialized data: " << serializedData << endl;
  79.  
  80. // Deleting heap memory used
  81. ListNode* curr = head;
  82. while (curr != nullptr) {
  83. ListNode* temp = curr;
  84. curr = curr->next;
  85. delete temp;
  86. }
  87.  
  88. return 0;
  89. }
  90.  
Success #stdin #stdout 0.01s 5304KB
stdin
Standard input is empty
stdout
String to deserialise: 1,20,35,4,51,82,90,100
Deserialized list: 1 20 35 4 51 82 90 100 
Serialising the same deserialised list.... 
Serialized data: 1,20,35,4,51,82,90,100,