#include <iostream>
using namespace std;
class node {
public:
int val;
node *next;
node *prev;
node(int val_) {
val = val_;
next = NULL;
prev = NULL;
}
};
void print(node *head) {
while (head != NULL) {
cout << head -> val << "<=>";
head = head -> next;
}
cout << endl;
}
node * create() {
node *head = NULL;
node *iter = head;
for (int i = 1; i <= 6; i++) {
if (i == 1) {
head = new node(i);
iter = head;
} else {
iter -> next = new node(i);
iter -> next -> prev = iter;
iter = iter -> next;
}
}
return head;
}
// NULL<-1<->2<->3<->4<->5<->6->NULL
// 1 -> right = 2 // 1 -> right = NULL
// 1 -> left = NULL // 1 -> left = 2
// 2 -> left = 1 // 2 -> right = 1
// 2 -> right = NULL // 2 -> left = NULL
// 1 2 3 4 5 6
// 6 5 4 3 2 1
node *reverse(node* head, node*& new_head) {
if (head == NULL || head -> next == NULL) {
if (new_head == NULL) {
new_head = head;
}
return head;
}
node* returned_node = reverse(head -> next, new_head);
returned_node -> next = head;
head -> prev = returned_node;
return head;
}
int main()
{
node *head = create();
print(head);
node *new_head = NULL;
node *head_ret = reverse(head, new_head);
new_head -> prev = NULL;
head_ret -> next = NULL;
print(new_head);
return 0;
}
No comments:
Post a Comment