Lately, I've been working on linked list questions on LeetCode, and I noticed that when dealing with linked lists (like sorting linked lists), people sometimes create a dummy node and return dummy->next. It is a pretty convenient act, but are there any bad outcomes from doing this (say, if I will delete it in the end to avoid a memory leak)? Or, are there any situations that make this act inappropriate?
The code below is an example, ohead is my dummy node:
/**
* Definition for singly-linked list.
* 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) {}
* };
*/
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
ListNode *ohead = new ListNode, *ehead = new ListNode;
ListNode *optr = ohead, *eptr = ehead;
bool isOdd = true;
for(auto ptr = head; ptr; ptr = ptr->next){
if(isOdd){
optr->next = ptr;
optr = optr->next;
}
else{
eptr->next = ptr;
eptr = eptr->next;
}
isOdd = !isOdd; //update isOdd
}
optr->next = ehead->next;
eptr->next = nullptr;
return (ohead->next);
}
};