Pop function and linked list implementation [closed] - c++

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Alright guys, so I know how the pop function works obviously. I also know that I need to set a LinkNode * top = head and that if top == NULL that you need to return NULL. I'm just not sure what I'm honestly supposed to do after that. The return is supposed to remove and return a value and the data type of the function is a pointer.
I'm not going to post my code on here unless people are honestly going to help me out because I've already been criticized greatly once and it was quite discouraging. :\

“I … know that I need to set a LinkNode * top = head and that if top == NULL that you need to
return NULL. I'm just not sure what I'm honestly supposed to do after that.”
Well, the things you mention have nothing to do with pop.
For a linked list, pop is about unlinking the first node. Depending on the level of abstraction the function might return (a pointer to) that node, or the node’s “value”, or nothing. At the lowest level of abstraction you want just the unlink functionality, which can go like this:
struct Node
{
Node* next;
double value;
};
Node* unlinked( Node*& p )
{
Node* const result = p;
p = p->next;
return result;
}
Then, as an example, a pop that destroys the node goes like this:
void pop( Node*& first )
{
delete unlinked( first );
}
while a pop that returns the value in the node goes like this:
double pop( Node*& first )
{
std::unique_ptr<Node> p( unlinked( first ) );
return p->value;
}
A subtle point here is whether the value is guaranteed to be copied before the node is destroyed. I'm just assuming it is. I leave it to the lawyers to find the standardese for that.
Cheers & hth.

Related

Why am I not getting any output, for my code on insertion in linked list? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I am trying to create a singly linked list by inserting nodes at end, and despite having no errors I am unable to print my linked list. Please help me debug my code.
I tried online compiler on codechef and it shows SIGSEGV Runtime error. What is this supposed to mean?
struct node
{
int data;
struct node *next;
};
void insert(struct node *root,int data)
{
struct node *temp=new(struct node);
if(root==NULL)
{
temp->data=data;
temp->next=NULL;
}
root->next=temp;
temp->data=data;
temp->next=NULL;
}
void print(struct node *root)
{
struct node *temp;
temp=root;
while(temp!=NULL)
{
cout<<temp->data;
temp=temp->next;
}
}
int main()
{
struct node *root=NULL;
insert(root,1);
insert(root,2);
insert(root,3);
insert(root,4);
print(root);
return 0;
}
Please help me debug my code.
OK lets try a dry run.
Imagine your list is empty and you are inserting your first item. So root equals NULL and we call insert.
1) first thing
struct node *temp=new(struct node);
You allocate a new node, and set temp equal to it, so far so good.
2) next thing
if(root==NULL)
this is true as explained in the preamble, so we enter the if statement
3) next thing
temp->data=data;
temp->next=NULL;
these statements in the if body get executed and initialise the newly allocated object. It's not clear why you only want to do this when root == NULL, I would think you would want to initialise the newly allocated node always. But anyway, so far no errors.
4) next thing
root->next=temp;
Now here's the error. Ask yourself, what is the value of root at this point? When we started it was NULL, has anything changed it since? The answer of course is no, so you are dereferencing a NULL pointer. That explains the error.
You need to be able to look at the code you've written and see it for what it really does. The ability to dry run your code like I did above is a very valuable skill to have.
Unfortunately your code really is not very close to being correct. So I think the best thing would be to look at some working code and see how it operates and then start again.

deleting pointer and use a field of the deleted object [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Here is the snippet of code that confuses me :
T* pop(){
if(head == 0)
return 0;
T* result = head->data;
Link* oldHead = head;
head = head->next;
delete oldHead;
return result;
}
The result pointer is maked to point to the "data field" of head's object. After that, head is deleted. Does not result have to point to null or a blank space since the data field is deleted together with head ?
Does not result have to point to null or a blank space since the data field is deleted together with head?
When you execute
delete oldHead;
the memory for oldHead is deallocated. However, unless you also delete data in the destructor of Link, data continues to be a valid pointer. Hence, it's ok to return result and continue to use the return value in the calling function.
If you have
Link::~Link() {}
there is no problem.
However, if you have
Link::~Link() { delete data; }
there is a problem.

Replacing Nodes in the nth position Link List [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
so i want to Write code to implement the replaceNode(…) function that takes pointers to OldNode and
NewNode as inputs using the function header given below. Also include code for the special
cases where OldNode is the head or tail nodes of the list. Assume the list is never empty
before this function is called and that all nodes have been created dynamically
void List::replaceNode(Node *OldNode, Node *NewNode)
{
//write code here
}
i have no idea how to go about doing this can some one please help me with this
CASE 1: where OldNode is neither HEAD or TAIL (Singly LinkedList)
You need to know about the node pointing the OldNode, lets call it *PrevPntr & the node which oldNode is pointing to.
Then it will be something like:
`PrevPntr->next = NewNode;
NewNode->next = OldNode->next
else
just replace the DATA of OldNode by data of NewNode (some constraints will be there in this case).
CASE 2: where OldNode is HEAD (Singly LinkedList).
Then it will be something like:
`
NewNode->next = OldNode->next
CASE 3: where OldNode is TAIL (Singly LinkedList).
You need to know about the node pointing the OldNode, lets call it *PrevPntr.
Then it will be something like:
`PrevPntr->next = NewNode;

Why did my C++mprogram stop working after being compiled? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm a computer science student and have been coding with Java for the past year. Now I'm interested in learning C++. The first program that I wanted to code with C++ is an implementation of stack using linked list, which I have coded before using java. I pretty much have no idea what I'm doing and basically just writing what I thought was right until I got no compile error. So I finally did it, my program got no compile error, but when I ran it, a pop-up appeared saying that my 'Stack.exe has stopped working'
Here's my code:`
#include <iostream>
using namespace std;
class Stack;
class Node;
class Node
{
public:
string element;
Node *next;
Node(string, Node);
};
Node::Node(string element, Node next)
{
this -> element = element;
*(this -> next) = next;
}
class Stack
{
private:
Node *tos;
public:
Stack()
{
tos = NULL;
}
void push(string str)
{
tos = new Node(str, *tos);
}
string peek()
{
return tos->element;
}
string pop()
{
string temp = tos->element;
tos = (tos->next);
return temp;
}
};
int main(void)
{
Stack bob;
bob.push("Wow");
bob.push("Wiw");
cout << bob.peek();
return 0;
}
Can someone tell me what I did wrong? I did it like this because this was how I did it with Java.
Thank you :D
You're dereferencing null or undefined pointers in a couple places. First let's look at your Node constructor:
*(this -> next) = next;
Since next hasn't been defined yet, dereferencing it leads to undefined behavior. In practice, next will point to some random place in memory that you probably don't own, so writing to it will cause a program crash. Your Node constructor should take a pointer to Node as its second parameter instead of taking a Node by value:
Node::Node(string element, Node* next)
: element{element},
next{next}
{}
Note that I've also initialized Node's members instead of default-initializing them and then assigning to them in the constructor's body.
After fixing Node's constructor, you'll also need to fix Stack::push to pass a pointer instead of an object:
void push(string str)
{
tos = new Node(str, tos);
}
Note that even after fixing the crashing problem, you'll still leak memory when you pop from your Stack (or when a Stack is destroyed). You need to delete anything you new, or better yet use std::shared_ptr<Node> instead of raw Node*s.

Why can't i print binary tree? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I created a class binary search tree.
but the problem is when i print the tree it crashes.
i think it can be an endless recursion in function print().
Here is my code
struct node{
node *l,*r;
int data;
};
class BinTree
{
private: node *root;
public:
BinTree(){ root=NULL; }
void add(int a){ add_node(a,root); };
void add_node(int a, node *rot)
{ node *curr; curr=rot;
if(curr==NULL)
{
curr=new node;
curr->data=a;
curr->l=NULL;
curr->r=NULL;
return;
}
if(a>=curr->data) curr=curr->r,add_node(a,curr);
if(a<curr->data) curr=curr->l,add_node(a,curr);
}
void print(){ inorder(root); }
void inorder(node *curr)
{
if(curr->l!=NULL) inorder(curr->l);
cout<<curr->data<<" ";
if(curr->r!=NULL) inorder(curr->r);
}
};
Can anyone help me?
In your add_node method, you never actually assign a value to the root. It should be something like this:
if(curr==NULL)
{
curr=new node;
curr->data=a;
curr->l=NULL;
curr->r=NULL;
root = curr;
return;
}
But, for the future, I have the same advice as Basile - use your compiler and your debugger to your advantange.
Your add_node is broken. If curr is NULL, it creates a new node but it never actually adds it to the existing tree. Thus all additions you make are effectively ignored and the tree stays empty.
The inorder function dereferences curr without checking whether it is NULL, and print calls it without checking whether root is NULL. Thus, your crash most likely is caused by tryin to print out an empty tree and then dereferencing a null pointer.
Learn how to use a debugger. Enable all warnings in the compiler.
On Linux, this means compile with g++ -Wall -g and debug with gdb