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* reverse(DoublyLinkedListNode* head) {
  17. DoublyLinkedListNode* current = head;
  18. DoublyLinkedListNode* newHead = nullptr;
  19.  
  20. while (current) {
  21. swap(current->next, current->prev);
  22. newHead = current;
  23. current = current->prev;
  24. }
  25.  
  26. return newHead;
  27. }
  28.  
  29. void printList(DoublyLinkedListNode* head) {
  30. while (head) {
  31. cout << head->data << " ";
  32. head = head->next;
  33. }
  34. cout << endl;
  35. }
  36.  
  37. int main() {
  38. DoublyLinkedListNode* head = new DoublyLinkedListNode(10);
  39. head->next = new DoublyLinkedListNode(20);
  40. head->next->prev = head;
  41. head->next->next = new DoublyLinkedListNode(30);
  42. head->next->next->prev = head->next;
  43.  
  44. head = reverse(head);
  45. printList(head);
  46.  
  47. return 0;
  48. }
  49.  
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
30 20 10