C++ Recursion - adding tree data to list in order - c++

My code is below - I'm trying to return to my main a list of aircrafts that I'm getting from a binary tree in order (smallesty to largest). For the code below, I get the root node twice. I've been working on it for hours... any suggestions?
Thanks,
Charlotte
std::list<Aircraft> Tree::buildList()
{
std::list<Aircraft> aircraftList;
if (_root != 0)
{
aircraftList = buildListHelp(_root, aircraftList);
aircraftList.push_front(*_root->getAircraftData());
}
return aircraftList;
}
std::list<Aircraft> Tree::buildListHelp(Node* node, std::list<Aircraft> aircraftList)
{
//aircraftList.push_back(*node->getAircraftData())
/*if (node->getLeft() != 0)
{*/
if (node==0)
return aircraftList;
buildListHelp(node->getLeft(), aircraftList);
//}
aircraftList.push_back(*node->getAircraftData());
/*if (node->getRight() != 0)
{*/
buildListHelp(node->getRight(), aircraftList);
//}
return aircraftList;
}

Assuming _root is declared as
Node* _root;
You are pushing it twice:
aircraftList.push_front(*_root->getAircraftData());
aircraftList.push_back(*node->getAircraftData());
In first call of buildListHelp

Related

Cycle remove from linklist gives segmentfault

void removeLoop(Node* head)
{
// code here
// just remove the loop without losing any nodes
Node* rab=head;
Node* tur=head;
while(rab && rab->next)
{
rab=rab->next->next;
tur=tur->next;
if(tur==rab)
break;
}
Node* temp=NULL;
if(rab && rab->next)
{
rab=head;
while(rab!=tur)
{
rab=rab->next;
temp=tur;
tur=tur->next;
}
temp->next=NULL;
}
}
This is my code implemented using floyd algo.
Question link
https://practice.geeksforgeeks.org/problems/remove-loop-in-linked-list/1#
It is giving segment fault on submission not able to identify the particular test case it's failing
According to question no need to return anything.
If we take the input as
4
1 2 3 4
1
then it will show the segmentation error.
Reason: If you run the code on this specific testcase, then after running the first while loop, both tur and rab will point to the head of the list. Now the condition of while loop inside the if loop will always return false. And after that, the code on the next line temp->next=NULL will give error because temp was initially NULL and this line will exhibit undefined behavior.
The correct program should be:
void removeLoop(Node* head)
{
Node* rab=head;
Node* tur=head;
while (rab && rab->next) {
rab = rab->next->next;
tur = tur->next;
if (rab == tur)
break;
}
if (tur == rab)
{
tur = head;
if(tur == rab) {
while(rab->next != tur) rab = rab->next;
}
else {
while (tur->next != rab->next) {
rab = rab->next;
tur = tur->next;
}
}
rab->next = NULL;
}
}

Binary Tree level order insertion c++

I want to insert in the tree but not using any other data structures like queue. I want to insert in level order and no matter what I code, it doesn't. Also I couldn't find any code without queues or things like that.
Here is my attempt;
void insert(int x) {
if (root == NULL) {
root = new node(x, NULL, NULL);
return;
}
node *temp = root;
node *prev = root;
while (temp != NULL) {
if (temp->left != NULL) {
prev = temp;
temp = temp->left;
} else if (temp->right != NULL) {
prev = temp;
temp = temp->right;
}
}
if (temp->left == NULL)
prev->left = new node(x, NULL, NULL);
else if (temp->right == NULL)
prev->right = new node(x, NULL, NULL);
}
I don't have a link for recursive insertion but it should work like this:
bool recursion(node * current_node, node * to_insert, int &max_depth, int cur_depth) {
if(max_depth < cur_depth) {
max_depth = cur_depth;
}
for (auto & current_child : {current_node->left, current_node->right})
if(current_child == NULL) {
if( max_depth > cur_depth ) {
current_child -> left = to_insert;
return true;
}
} else {
if(recursion(current_child, to_insert, max_depth, cur_depth + 1)) {
return true;
}
}
return false;
}
This does depth-first-search (not breadth-first, I was mistaken above, they are very similar in trees) from left to right. So we will first find the left-most leaf, then the one right next to it and so on. We will always track how deep we are in the tree. If at one point we find a node on the second deepest layer that hasn't got a child, it will add the node we want to insert at this point and recurse up the tree. Due to the order in which we traverse the tree, this will find the left most open spot, so exactly what you want.
This method can return false if the submost layer of the tree is full. Then we have to go down to the left-most leaf and insert the node at its left child. One can also save this leaf somehow when we first find it, but that seemed more complicate to me then just searching it again (this can be done without problem in a for-loop).
You can replace the recursive method by an iteration with a stack (there are many sources on the internet explaining how to make a recursive depth-first-search to a iterative one).
I don't really like the in-out-parameter max_depth but it was the easiest to do this.

Remove Duplicates from sorted list not passing all testcases

This is a question on leetcode. For some reason my code only works for 7/164 test cases. i would like to know why my algorithm is not efficient.
what is a solution to this? what is wrong with my code?
here is link to the problem
https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/
edit: i have taken suggestions and edited code but my algorithm is still not passing, i am getting a time limit exceed error. is the algorithm efficient?
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
ListNode* current = head;
ListNode* nex;
while(current!=NULL){
nex=current->next;
if (nex==NULL)
break;
if(current->val==nex->val)
current->next=nex->next;
if (current->next==NULL)
break;
current==current->next;
if(current->next==NULL)
break;
}
return current;
}
};
nex is not initialized. You try to compare it with NULL before it is initialized.
You remove duplicates of the neighbor pairs only. It is OK for sorted lists.
You get into memory leaks.
The final two if are odd.
I think you return from the function not what is expected.
Used == where = should be used.
Your should not change current after current->next changed.
while (current && (nex = current->next)){
if (current->val == nex->val) {
current->next = nex->next;
delete nex;
} else {
current = current->next;
}
}
return head;
Remove Duplicates from Sorted List (JavaScript) -> try this one
let deleteDuplicates = (head) => {
let inArray = []
let check = head.reduce((a, c) => {
if(a[c]) a[c] = ++a[c];
else a[c] = 1;
return a
},{})
for (var i in check) {
if (check[i] == 1) inArray.push(Number(i))
}
return inArray;
}
let output = deleteDuplicates([3,7,4,4,2])
console.log(output)

Single Linked List: Null Pointer Exception when searching through list with while loop

Im having trouble with this method im trying to get to work. My assignment is to delete the first occurance of an element. It works fine when there is a element to delete in the list. But if i search for an element that is not in the list, it throws me a nullpointer exception on my while loop.
Cant seem to find the problem, i want the loop to stop after: either found element or when temp.next == null(aka at the end of the list).
Can someone point me in the right direction please?
public void deleteFirstOccurance(int data)
{
Node temp = head;
boolean foundElement = false;
if(head==null) //Sjekker om listen inneholder elementer
{
System.out.println("There are no elements in list");
}
else
{
if(temp.element==data) //Sjekker første node
{
head = temp.next;
System.out.println(temp.element+" is deleted");
elementCount--;
foundElement = true;
}
else
{
while(temp.next != null || temp.next.element != data) //Leter fra node sin next frem til den finner data eller treffer null
{
temp = temp.next;
}
if(temp.next.element == data)
{
System.out.println(temp.next.element+" is deleted");
temp.next= temp.next.next;
elementCount--;
foundElement = true;
}
}
}
if(!foundElement)
System.out.println("No elements found");
}//Oppgave3
The exception is thrown, because you are getting the value of temp.next.element before checking if temp.next is null.
The same thing after while loop finishes: you have if (temp.next.element == data) but temp.next may be null here. At this point it is either the next element is the one you are looking for, or null. So a check if (temp.next != null) should suffice.
Also the condition should have &&, not ||: you want to continue the loop, while you have a next element and this element is not what you are looking for.
So to fix the issues, replace while(temp.next.element != data || temp.next != null) with while (temp.next != null && temp.next.element != data), and replace if (temp.next.element == data) after the while loop with if (temp.next != null)

C++ Linked List Search Error: STATUS_ACCESS_VIOLATION

I am writing a program that adds, deletes, and displays nodes (that are doubly linked) and their components, but whenever I try to retrieve a node and display it's components I get this error:
2 [main] a 4640 exception::handle: Exception: STATUS_ACCESS_VIOLATION
2875 [main] a 4640 open_stackdumpfile: Dumping stack trace to a.exe.stackdump
I have narrowed it down to the search function within my .h file that is supposed to search to see if there is a node within the linked list that account number being searched. The function returns the node that comes before it, or the "previous" node.
Here is my search function:
bool searchListByAcctNum (int searchKey, nodePtr *prevOut)
{
bool found = false;
nodePtr p = headNum;
nodePtr prev = NULL;
while (p != NULL)
{
if (p->acctNum < searchKey)
{
prev = p;
p = p->nextNum;
}
else
{
if (p->acctNum == searchKey)
found = true;
p = NULL;
}
}
*prevOut = prev;
return found;
If anyone could help me at all, I'd appreciate it!
It looks like your list may be corrupted, or the pointer you're passing to receive the previous node is invalid, since that code looks okay. However, it seems to me that it could be written in a much simpler manner:
bool searchListByAcctNum (int searchKey, nodePtr *prevOut) {
/// Start at beginning of list, use pointer variable to hold previous.
nodePtr p = headNum;
*prevOut = = NULL;
// Process entire list, will exit early if need be.
while (p != NULL) {
// If past it, just return false, caller should ignore prevOut.
if (p->acctNum > searchKey)
return false;
// If equal, return true, prevOut holds previous or NULL if found at start.
if (p->acctNum == searchKey) {
return true;
// Save previous and advance to next.
*prevOut = p;
p = p->next;
}
// Reached end of list without finding, caller should ignore prevOut.
return false;
}