Problem Statement: Given the head of a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
First Code that provides correct output
ListNode* partition(ListNode* head, int x) {
ListNode* small = new ListNode(-1);
ListNode* large = new ListNode(-1);
ListNode* smallhead = small;
ListNode* largehead = large;
while(head) {
if(head->val<x) {
small->next = head;
small = small->next;
head = head->next;
small->next = NULL;
}
else {
large->next = head;
large = large->next;
head = head->next;
large->next = NULL;
}
}
small->next = largehead->next;
return smallhead->next;
}
Second Code that provides wrong output
ListNode* partition(ListNode* head, int x) {
ListNode* small = new ListNode(-1);
ListNode* large = new ListNode(-1);
ListNode* smallhead = small;
ListNode* largehead = large;
while(head) {
if(head->val<x) {
small->next = head;
small = small->next;
small->next = NULL;
head = head->next;
}
else {
large->next = head;
large = large->next;
large->next = NULL;
head = head->next;
}
}
small->next = largehead->next;
return smallhead->next;
}
And this is the defination of ListNode Structure
struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
I just want to know why these two codes show different output.