THs following code is crashing, and I'm unsure why. Trying to count the number of times an integer is found in the following linked list..However xcode keeps saying the int count=0 from the main is breaking a thread?
#include <iostream>
using namespace std;
struct Node {
int val;
Node *next;
};
int countNum (Node *head, int key);
Node* cons (int x, Node* p);
int main()
{
Node *head = (1,cons(2,cons(2,(cons(4,(cons(5,nullptr)))))));
int counts=0;
counts= countNum(head,2);
cout<< counts<< head;
return 0;
}
Node* cons (int x, Node* p){
Node *q=new Node;
q->val=x;
q->next=p;
return p;
}
int countNum (Node *head, int key) {
int count=0;
if (head==nullptr)
return 0;
Node *follow=head;
while (follow!=nullptr) {
if(follow->val==key)
count++;
follow=follow->next;
}
cout<<count;
return count;
}
use Node *head = cons(1,cons(2,cons(2,(cons(4,(cons(5,nullptr)))))));
I think you want to return a pointer to the current node instead of the next node. Also I don't think you can do:
Node *head = (1, ptrToNextNode);
Something like this might work:
struct Node *head = malloc(sizeof (struct Node));
head->value = 1;
head->next = cons(2,cons(2,(cons(4,(cons(5,nullptr))))));
...
Node* cons (int x, Node* p)
{
Node *q=new Node;
q->val=x;
q->next=p;
return q;
}
Related
I am not getting how to run the concatenate function using both Node and LinkedList as classes. If anyone knows how to do it, please let me know.
Here I have created two classes one for linked list and the former one for Node creation.
Using create function and passing array as Linked list input. Also, I am getting the headref using getHead() and getHead2() functions which give the starting pointer of first and second Linked List respectively.
#include <iostream>
using namespace std;
class Node{
public:
int data;
Node* next;
Node(){
data=0;
next=NULL;
}
Node(int data){
this->data=data;
this->next=NULL;
}
};
class LL{
Node* first, *second;
public:
LL(){
first=second=NULL;
}
void create(int arr[], int n){
Node* t, *last;
first=new Node();
first->data= arr[0];
first->next=NULL;
last=first;
for(int i=1;i<n;i++){
t=new Node();
t->data=arr[i];
t->next=NULL;
last->next=t;
last=t;
}
}
void create2(int arr[], int n){
Node* t, *last;
second=new Node();
second->data= arr[0];
second->next=NULL;
last=second;
for(int i=1;i<n;i++){
t=new Node();
t->data=arr[i];
t->next=NULL;
last->next=t;
last=t;
}
}
Node* getHead(){
return first;
}
Node* getHead2(){
return second;
}
void display(Node* p){
while(p){
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
void concatLL(){
Node* p=first;
while(p->next){
p=p->next;
}
p->next=second;
second=NULL;
}
};
int main()
{
LL l,l2;
int arr[]={1,2,3,4,5,6,7};
int arr2[]={2,5,7,8,9};
int n=sizeof(arr)/sizeof(arr[0]);
int n2=sizeof(arr2)/sizeof(arr2[0]);
l.create(arr,n);
l2.create2(arr2,n2);
cout<<"Displaying first LL"<<endl;
l.display(l.getHead());
cout<<"Displaying second LL"<<endl;
l2.display(l2.getHead2());
cout<<"Displaying Linked list after concatination"<<endl;
l.concatLL();
l.display(l.getHead());
return 0;
}
p is equal to NULL when executing p->next=second; in concatLL() causing undefined behaviour since the while loop runs until p == NULL. You should use while(p->next) instead of while(p) and check that first is not a null pointer before.
A linked list is still a Node, and as others said, at the end of your while loop p is pointed to NULL. You can't NULL->second=second neither NULL=second, so change your while loop stop condition:
void concatLL(){
Node* p=first;
while(p->next){
p=p->next;
}
p->next=second;
second=NULL;
}
};
Here is my solution:
#include <iostream>
using namespace std;
struct Node {
Node* next;
int value;
Node(int value) {
this->value = value;
this->next = NULL;
}
Node(int n, int a[]) {
value = a[0];
next = NULL;
Node* p = this;
for (int i = 1; i < n; i++) {
p->next = new Node(a[i]);
p = p->next;
}
}
void concat(Node* head) {
Node* p = this;
while (p->next != NULL) {
p = p->next;
}
p->next = head;
}
void display() {
Node* current = this;
while (current != nullptr) {
cout << current->value << " ";
current = current->next;
}
cout << endl;
}
};
int main() {
int a[] = { 1, 2, 3, 4, 5 };
int b[] = { 6, 7, 8, 9, 10 };
Node* list1 = new Node(5, a);
Node* list2 = new Node(5, b);
list1->display();
list2->display();
list1->concat(list2);
list1->display();
return 0;
}
So I made these two simple functions regarding linked lists. One adds a node at the front and the other just displays the linked list in a sequence front to end. I'm wondering why this code wouldn't give me any output.
#include <iostream>
using namespace std;
class Node
{
public:
int data;
Node *next;
};
Node *head;
void addFront(Node *head, int item)
{
Node *temp = new Node();
temp->data = item;
temp->next = head;
head = temp;
}
void traverse(Node *head)
{
Node *temp = head;
while(temp!=NULL)
{
cout << temp->data << " ";
temp = temp->next;
}
}
int main()
{
addFront(head, 1);
addFront(head, 2);
addFront(head, 3);
traverse(head);
}
You're operating on a copy of head pointer in addFront(). You have
to pass a pointer to pointer:
void addFront(Node **head, int item)
The entire code could look like this:
#include <iostream>
using namespace std;
class Node
{
public:
int data;
Node *next;
};
Node *head;
void addFront(Node **head, int item)
{
Node *temp = new Node();
temp->data = item;
temp->next = *head;
*head = temp;
}
void traverse(Node *head)
{
Node *temp = head;
while(temp!=NULL)
{
cout << temp->data << " ";
temp = temp->next;
}
}
int main()
{
addFront(&head, 1);
addFront(&head, 2);
addFront(&head, 3);
traverse(head);
}
Argument of addFront is input as well as output. (Node *head)
It needs to be passed as referenced
I hope this question wasn't asked before. I tried searching for an answer but couldn't find any. I'm trying to learn pointers and linked lists in C++. this is my code so far
#include <iostream>
using namespace std;
struct node{
int value;
node* next;
};
node createNode(int value){
node temp;
temp.value = value;
temp. next = NULL;
return temp;
}
void add( node*& head, int value){
node temp = createNode(value);
// the problem is in this if statement
if (head->next == NULL){
head->next = &temp;
}
}
int main() {
node* head;
add(head,4);
cout<<head->next->value;
return 0;
}
if I try to grab the address of temp into the head, in my main function, the cout will print this value "1634545454" and If I move the code line "head->next = &temp;" outside of the if statement, it'll print the correct result which is 4. I don't understand why is that happening! what is that value? is the condition inside the if statement doing anything to the address, or the value of head->next?
You're declaring temp as a node (note the lack of *), i.e. a local variable. So it's automatically being freed at the end of the function.
Roughly speaking, you need to decide how you want to manage your memory. If you're going to do it all yourself, you need to use node* everywhere and remember to free your data structures when they go out of scope. But the more modern, safer approach would be to use unique_ptr<node>, which correctly captures that your node owns its next pointer. In this way, the data will be freed automatically when the time comes, but not before.
as #Silvio Mayolo mentioned you have two choices of using self managing memory or smart pointers , but as your base code was written in the self managing way ive fixed some of the pointers in your code.
the node pointer named head was not memory allocated and the temp variable most be a pointer so that the lifecycle dosent exceeds ,and if your using c++11 and above using nullptr would be better.
#include <iostream>
using namespace std;
struct node{
int value;
node* next=nullptr;
};
node* createNode(int value){
node* temp=new node;
temp->value = value;
temp->next = nullptr;
return temp;
}
void add( node* head, int value){
node* temp = createNode(value);
if (head->next == nullptr){
head->next = temp;
}
}
int main() {
node* head=new node;
add(head,4);
cout<<head->next->value;
return 0;
}
#include<iostream>
using namespace std;
struct node{
int value;
node* next=NULL; //node* next;
};
node* createNode(int value){ //node createNode(int value){
node* temp=new node; //node temp;
temp->value = value;
temp->next = NULL;
return temp;
}
void add( node* head, int value){ //void add( node*& head, int value){
node* temp = createNode(value); //node temp = createNode(value);
if (head->next == NULL){
head->next = temp; //head->next = &temp;
}
}
int main() {
node* head=new node; //node* head;
add(head,4);
cout<<head->next->value;
return 0;
}
I want to know what is the problem in creat_list2 function..
I have a problem in this code and as i knew it's in the creat_list2 cause the program run Successfully
when i stop this function it ask the user to enter a numbers that will be stored in the list 1 then print them but the problem as i saw is in the second fuction that creat the second list...,I have to submit my assignment tomorrow so I wish if any body can help me to solve this problem.
#include<iostream>
using namespace std;
struct node{
int x;
node *next;
};
struct snode{
int y;
snode *next;
};
creat_list1(node *&head, node *&tail)
{
int num;
cout<<"enter number\n";
cin>>num;
while(num!=0)
{
node *np=new node;
np->x=num;
if(head==nullptr)
head=np;
else
tail->next=np;
tail=np;
tail->next=nullptr;
cout<<"enter number again\n";
cin>>num;
}
}
creat_list2(node *&head, snode *shead, snode *stail)
{
int sum=0;
while(head!=nullptr)
{
for(int i=0;i<head->x;i++)
sum+=i;
snode *np= new snode;
np->y=sum;
if(head==0)
shead=np;
else
stail->next=np;
stail=np;
stail->next=nullptr;
}
head=head->next;
}
void print_list1 (node *head)
{
while(head!=nullptr)
{
cout<<head->x<<"\t";
head=head->next;
}
}
void print_list2(snode *shead)
{
while(shead!=nullptr)
{
cout<<shead->y<<"\t";
shead=shead->next;
}
}
main()
{
node *head=nullptr, *tail=nullptr;
snode *shead=nullptr, *stail=nullptr;
creat_list1(head,tail);
creat_list2(head,shead,stail);`enter code here`
print_list1(head);
print_list2(shead);
}
There are couple of issues with yours code,
creat_list2(node *&head, snode *shead, snode *stail) if u updated
head like head=head->next; it will reflect at the main.
shead and stail are just a local pointer and any update to just a pointer like stail=np;will not have any changes at the `main
There seems to be typo if(head==0) shead=np; instead it should be
if(shead==0) shead=np; which is causing null pointer exception.
I tried to fix the error at creat_list2 but functionality is still ambiguous to me,
void creat_list2(const node *head, node *&shead, node *&stail) //updated in argument
{
int sum = 0;
while (head != nullptr)
{
//for (int i = 0; i < head->x; i++)
// sum += i;
node *np = new node;
np->x = sum;
if (shead == 0) //error : head instead shead
shead = np;
else
stail->next = np;
stail = np;
stail->next = nullptr;
head = head->next;
}
}
I'm writing a piece of code to append a node to the end of a singly linked list, but it seems that it doesn't append anything at all. Can anybody give me some idea of what I'm doing wrong?
#include<iostream>
using namespace std;
struct Node{
int val;
Node* next;
Node(int v) : val(v), next(NULL) {}
};
void append(Node &head, int d){
Node n = head;
while(n.next != NULL){
n = *n.next;
}
Node end(d);
n.next = &end;
}
int main(){
Node head(0);
for(int i=1;i<5;i++){
append(head, i);
}
Node n = head;
while(n.next != NULL){ //print the linked list, result is 0
cout << n.val<<" ";
n = *n.next;
}
cout<<n.val<<endl;
return 0;
}
EDIT: I changed the append() method to append a dynamically-allocated node each time, but it still doesn't work.
void append(Node &head, int d){
Node n = head;
while(n.next != NULL){
n = *n.next;
}
Node* end = new Node(d);
n.next = end;
}
You append the local object Node end(d); to the end of the linked list. This object is destroyed upon exist from append and the last list element points to a non-existent object.
A few issues with this.
You make a copies in your append function here Node n = head; and here n = *n.next. You then then finally make a change to the copy rather than the original.
You are assigning Node end(d) on the stack. When append returns it goes out of scope and is deleted.
You can fix both with,
#include<iostream>
#include <memory>
using namespace std;
struct Node{
int val;
std::shared_ptr<Node> next;
Node(int v) : val(v), next(nullptr) {}
};
void append(Node &head, int d){
Node* n = &head;
while(n->next != nullptr){
n = n->next.get();
}
n->next = std::make_shared<Node>(d);
}
int main(){
Node head(0);
for(int i=1;i<5;i++){
append(head, i);
}
Node n = head;
while(n.next != nullptr){
cout << n.val<<" ";
n = *n.next;
}
cout<<n.val<<endl;
return 0;
}
For the edited Question:
You are copying the head to n, then modify n. At the end of your append function, n is destroyed, but head was never touched.