Im trying to swap position of two node in doubly linked list without swapping the data, this is my code, it came up with wrong answer when run through this testcase:
the list length: 20
the list: 2158 2398 300 2268 3655 765 3792 4038 1761 4762 1292 3200 3882 962 488 1938 3757 3122 302 640
positions to swap: 9 12
the right answer is: 2158 2398 300 2268 3655 765 3792 4038 3200 1292 4762 1761 3882 962 488 1938 3757 3122 302 640
but mine got a bit different:2158 2398 300 2268 3655 765 3792 4038 3200 4762 1292 1761 3882 962 488 1938 3757 3122 302 640. I need some help here
/*struct ListNode {
int val;
ListNode *left;
ListNode *right;
ListNode(int x = 0, ListNode *l = nullptr, ListNode* r = nullptr) : val(x), left(l), right(r) {}
};
*/
ListNode* reverse(ListNode* head, int a, int b) {
//To Do
if(a==b) return head;
ListNode* h = head;
ListNode* anode = new ListNode;
ListNode* bnode = new ListNode;
int n(1);
for(int i(1); h!= nullptr; i ){
if(i == a){
anode = h;
}
if(i == b){
bnode = h;
// break; // now h = bnode
}
n;
h= h->right;
}
ListNode* bleft = new ListNode;
ListNode* bright = new ListNode;
bright = bnode->right;
bleft = bnode->left;
bnode->right = anode->right;
bnode->right->left = bnode;
if(a==1){
}
else{
bnode->left = anode->left;
bnode->left->right = bnode;
}
anode->left = bleft;
bleft->right = anode;
if(bright ==nullptr){
anode->right = nullptr;
}
else{
anode->right = bright;
bright->left = anode;
}
if(a==1) return bnode;
return head;
}
CodePudding user response:
The right answer, as well as the name of the function you are supposed to write, suggest that you should reverse a sublist. Your code doesn't attempt to do that. It swaps positions of the first and the last nodes of the sublist. These are two different operations. The reverse operation generally needs a loop to iterate over the nodes of the sublist.
On an unrelated note, you code has four totally useless new
expressions. They contribute nothing but memory leaks. Just remove them.