Create and print a Linked list - c++

#include <iostream>
using namespace std;
struct node
{
int num;
node * next;
};
//Create a list, if list is not empty have at least first middle and last node
void cList (node *);
//inserts a node
void iANode(node *);
//Inserts in order
void iIOrder(node *);
void main(){
int numM;
node *list, *current;
list = new node;
current = list;
cout<<"Input"<<endl;
cin>>numM;
//creates a list
void clist(node * record){
node * head = new node;
(*head).d1=0;
(*head).next =0;
return head;
}
//inserts a node
void iANode(node * record)
{
(*newnode).next = (*pred).next;
(*pred).next= new node;
++(*phead).counter;
}
//inserts in order
void iIOrder(node * new node, node*head){
node *pred = head;
int i = (*new node).d1;
node*succ=(*pred);
}
}
I am trying to create a linked list and sorting it after each user input.
Currently getting a whole lot of compile errors. Id appreciate if someone could help and point me in the right direction.
Thanks in advance.
Compile Errors:
Local function definitions are illegal for "cList" and "iANode"
";" missing after "node * record)"in cList
Expecting ")" after node in "void iIOrder(node * new node"

use struct node *next, instead of node *next. Same applies to *list and *current
some compilers does not accept void main(), try using int main()
put all function implementation outside main()
declare *current and *list as global variables (outside main())
C++ is case sensitive, cList is different from clist. fix cList implementation
not an error, but use -> operator: head->num = 0;
there is no field d1 in structure node (function cList and iIOrder). Use field num.
to nullify a pointer use NULL instead of 0
cList function is void, but you are returning a pointer, change return value
in iANode function you are using a lot of undeclared variables. You probably want to use *list, *current and *record.
There is a bunch of analythic errors, but you asked for syntax errors. Maybe you will find more errors later, try to fix theses first.

Related

How to create a node using the structure definition if the integer value is passed to a function?

The Definition of the structure is as follows.
//Structure of the linked list node is as follows:
struct Node {
int data;
struct Node* next;
Node(int x) {
data = x;
next = NULL;
}
};
I have to complete this function which I have completed this way. I am trying to create a Node using the newData parameter passed in the function definition. But it shows the error which I have attached below.
// function inserts the data in front of the list
Node* insertAtBegining(Node *head, int newData) {
//Your code here
struct Node* newNode(newData);
struct Node* temp;
temp=head;
head=newNode;
newNode->next=temp;
}
I get this error while I am create a node by passing newData as parameter to struct Node *newNode(newData);
In function Node* insertAtBegining(Node*, int):
prog.cpp:67:32: error: invalid conversion from int to Node* [-fpermissive]
struct Node *newNode(newData);
Thank You for your help.
Your constructor returns a Node, not a Node*, so when you try to initialize newNode, the compiler thinks you're trying to create a pointer using an int. Instead you should be expecting your constructor to give you a Node:
Node newNode(newData);
Your insertAtBegining() implementation needs to create a new Node object. You aren't doing that. Right after your teacher's Your code here comment, your attempt has defined a "Node pointer" variable (whose type is Node*), but your attempt hasn't initialized that to any Node object (data that would have been passed to an object's constructor isn't the same as the object itself).
Also, you don't need to keep repeating struct that way that us old guys used to do with old-fashioned C code.
Lastly, you seem to also want to return the list's new head node back to the function's caller, but are unclear how you want to achieve that. There are two ways. The way that your code seems to be leaning towards is returning the new head in the same head parameter. In that case, it should look like this:
void insertAtBegining(Node** head, int newData)
{
//Your code here
Node* newNode = new Node(newData);
Node* temp;
temp = *head;
*head = newNode;
newNode->next = temp;
}
(The head parameter could also have been a "reference to a Node*", instead of this "pointer to a Node*", by making appropriate changes to the code.)
The second option (which maintains your teacher's recommended function signature) is to return the new head via the function's return value:
Node* insertAtBegining(Node* head, int newData)
{
//Your code here
Node* newNode = new Node(newData);
newNode->next = head;
return newNode;
}

Deleting a linked list with specified data recursively

I want to delete a linked list recursively. I figured how to do this iteratively but I'm curious on how to do this. So far I have:
void deleteNodeRecursively(LinkedList *list, int value){
Node *curr=list->head;
if (list->head==NULL){
return;
}
else if (list->head->data==value){
Node *x=list->head->next;
delete list->head;
list->head=x;
}
else{
LinkedList *newlist;
newlist->head=list->head->next;
deleteNodeRecursively(newlist,value);
}
}
Where I defined
struct LinkedList{
Node *head;
};
struct Node{
int data;
Node *next;
};
I can remove the head if need be, but I can't figure out how to remove the body or tails and then correctly stitch up the list, let alone do it recursively. How do I proceed? Why won't this work?
EDIT: Removed question marks and replaced with code that I thought would work.
Assuming you have a "correct" constructor and destructor for your Node data.
You would have to track address of the deletion, for which you could pass a double pointer or a reference to pointer.
void deleteNodeRecursively(Node** list, int value){
// ^^^ double pointer to track address withing recursive call
Node *curr= *list ;
if (curr ==NULL){ // Base case for recursion
return;
}
else if ( curr->data==value){ // If node to be deleted is found
*list = curr->next; // Update the address for recursive calls
delete curr; // Delete this current "got" node
}
// Else simple recurse into
deleteNodeRecursively( &(*list)->next, value );
}
Note: This implementation will delete all nodes with data that matches value .

Getting wrong output with custom linked list implementation

I am learning list in C++ independently, and i have searched many websites about it. However, almost every approach to create a list is the same.
They usually create a struct as the node of a class. I want to create a class without using struct. So I created a class name ListNode which contains an int data and a pointer.
The main member functions of my class are AddNode and show.
Although, this program compiles successfully, it still does not work as I wish.
Here is the header file:
#ifndef LISTNODE_H_
#define LISTNODE_H_
#pragma once
class ListNode
{
private:
int data;
ListNode * next;
public:
ListNode();
ListNode(int value);
~ListNode();
void AddNode(ListNode* node,ListNode* headNode);
void show(ListNode* headNode);
};
#endif
Here is the implementation:
#include "ListNode.h"
#include<iostream>
ListNode::ListNode()
{
data = 0;
next = NULL;
}
ListNode::ListNode(int value)
{
data = value;
next = NULL;
}
ListNode::~ListNode()
{
}
void ListNode::AddNode(ListNode* node,ListNode* headNode) {
node->next = headNode;
headNode =node;
}
void ListNode::show(ListNode* headNode) {
ListNode * traversNode;
traversNode = headNode;
while (traversNode != NULL) {
std::cout << traversNode->data << std::endl;
traversNode = traversNode->next;
}
}
Main function:
#include"ListNode.h"
#include<iostream>
int main()
{
using std::cout;
using std::endl;
ListNode* head = new ListNode();
for (int i = 0;i < 3;i++) {
ListNode* Node = new ListNode(i);
head->AddNode(Node, head);
}
head->show(head);
return 0;
}
As far as I am concerned, the output should be
2
1
0
However, the output is a single zero. There must be something wrong in the AddNode and show function.
Could you please tell me what is wrong with these two functions?
When you call head->AddNode(node, head) you´re passing the memory directions which the pointers point, when the function arguments receive those directions, they are now pointing to the same directions, but those are another pointers, no the ones you declared in main. You could see it like this:
void ListNode::AddNode(ListNode* node,ListNode* headNode) {
/*when the arguments get their value it could be seen as something like:
node = Node(the one from main)
headNode = head(the one from main)*/
node->next = headNode;
/*Here you are modifying the new inserted node, no problem*/
headNode = node;
/*The problem is here, you´re modifying the memory direction
headNode points to, but the headNode argument of the function, no the one declared in main*/
}
So the pointer head in main() always points to the same first node you also declared in main().
In order to fix this you should change your code this way:
void ListNode::AddNode(ListNode* node,ListNode** headNode) {
/* second paramater now receives a pointer to apointer to a node */
node->next = *headNode;//the same as before but due to pointer syntaxis changes a bit
*headNode = node;//now you change the real head
}
And when you call it:
head->AddNode(Node, &head);//you use '&' before head
Now the real head, no the one in the function, will point to the last node you inserted.

In linked list formation, what is the code for adding a variable at the beginning?

I am trying to add and print a new node at the beginning of my linked list. But my code doesn't show the added data while printing in C++.
struct node{
int data;
node *next;
};
void add_begin(node *S, int k)
{
node *T;
T=new (node);
T->data=k;
T->next=S;
S=T;
}
void print(node *S)
{
cout<<"Elements of the node :\n";
while (S->next!=NULL)
{
cout<<S->data<<endl;
S=S->next;
}
cout<<S->data<<endl;
}
I am assuming that you would be calling this function passing in a node which is the head of a list and an int which is the new data and are expecting the node you passed in to be updated to the new node.
Unfortunately that is not what is happening. Inside the function add_begin it has its own pointer to the first node in the list so when you update it with S=T only pointer in the function is updated, not the one you passed in as well.
If you want to update the pointer you pass in you should pass it by reference (void add_begin(node *&S, int k)) or return the new node pointer from the function and assign it the external pointer manually.

headnode of singly Linked list has default value?

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
class Node{
public:
int data;
Node * next;
};
void Append(Node * head, int newdata){
Node * n = head;
if(n->next != NULL)
{
n = n->next;
}
n->data = newdata;
cout<<"data-> "<<newdata<<" inserted!"<<endl;
}
void Display(Node * head){
Node * n = head;
if(n->next != NULL)
{
cout<<"data->"<<n->data<<endl;
n = n->next;
}
cout<<"data->"<<n->data<<endl;
}
int main(int argc, char * argcv[])
{
Node * headnode;
int newdata = 20;
Append(headnode, newdata);
Display(headnode);
return 0;
}
The output of this program is:
data-> 20 inserted!
data->1
data->20
Why the headnode has been assigned a "1" data member here?
Besides the comments, the problem here is that you are sending a pointer to a Node in your append function without initializing the data and the pointer that it contains.
On the if(n->next != NULL) inside append, n->next will also be random data, meaning that you will assign the value 20 not to the "head" but to the node that the head points to.
That is why the value 20 is on the next node when printing, and random value of (in this case 1) is in your head node.
You need to use the new in order to allocate the Nodes in the memory, as dereferencing a pointer that isn't pointing to allocated memory will most likely cause segfaults.
Apart from the comments and answer by #Milan, I think the design of class Node can be better implemented. It's not always required to expose data members( i.e., Node::data ) and especially in this case. class Node can also have member functions that does appending a new link and display the linked list. To get an idea, think of the way the container std::list is implemented( i.e., its member functions ). Take the advantage of powerful feature, data hiding, in C++.