How do I remove these nodes from a linked list? - c++

When I run the code, it will not remove the nodes like I want it to. They stay on the list. I think that there may be issues with the .cpp and header file, but I am not sure. This is my first time messing with Linked Lists, so any help would be appreciated! Code:
#include <iostream>
#include "NumberList.cpp"
using namespace std;
int node(){
int i,j;
char answer;
NumberList list; //create a new linked list
bool MainMenu = true;
while (MainMenu){
cout<<"Please make a selection:\n1.Add a starting point\n2.Remove a starting point.\n3.Quit"<<endl;
cin>>answer;
if(answer == '1'){
bool keepGoing = true;
while (keepGoing){
cout<<"Enter the row: ";
cin>>i;
cout<<"Enter the column: ";
cin>>j;
list.add(i,j);
cout<<"You added "<<i<<"and "<<j<<endl;
//list.add(4,5);
//list.add(3,6);
cout<<"Here is the list: "<<endl;
list.displayList();
cout<<"Would you like to add another point? y/n"<<endl;
cin>>answer;
if (answer == 'y')
{
keepGoing=true;
}
else if (answer == 'n')
{
keepGoing=false;
}//end else
}
}
else if (answer == '2'){
int x,y;
cout<<"Here are the points chosen: "<<endl;
list.displayList();
cout<<"Which point do you want to remove?\nRow: "<<endl;
cin>>x;
cout<<"Column: "<<endl;
cin>>y;
list.remove(x,y);
cout<<"Updated list: "<<endl;
list.displayList();
}
else if (answer == '3'){
MainMenu = false;
}//end else if
else{
cout<<"Unable to process"<<endl;
}
}//end keepGoing
}
int main()
{
node();
}
NumberList.cpp:
#include "NumberList.h"
using namespace std;
void NumberList::add(int i, int j)
{
if (head == NULL)
head = new ListNode(i,j);
else
{
//The node is not empty. Use nodePtr to traverse the list
ListNode *nodePtr = head;
while (nodePtr->next != NULL)
nodePtr = nodePtr->next;
//nodePtr->next is NULL so nodePtr points to the last node.
//Create a new node and put it after the last node
nodePtr->next = new ListNode(i,j);
}
}
void NumberList::displayList()
{
ListNode *nodePtr = head; //Start at head of the list
while(nodePtr)
{
//Print the value in the current node
cout<<"("<<nodePtr->i<<","<<nodePtr->j<<")";
//Move onto the next node
nodePtr = nodePtr -> next;
}
}
void NumberList::remove(int x, int y)
{
ListNode *nodePtr, *previousNodePtr;
//if the list is empty, do nothing;
if (!head) {
cout<<"The list is empty"<<endl;
return;
}
//int i,j;
int j;
//Determine if the first node is the one to delete.
if (head-> i&&j == x&&y)
{
nodePtr = head;
head = head ->next;
delete nodePtr;
}
else
{
//Initialize notePtr to the head of the list;
nodePtr = head;
//Skip the nodes whose value member is not number
while(nodePtr != NULL && nodePtr-> i&&j != x&&y)
{
previousNodePtr = nodePtr;
nodePtr = nodePtr->next;
}
//Link the previous node to the next node after
// nodePtr, then delete nodePtr
if (nodePtr)
{
previousNodePtr -> next = nodePtr->next;
delete nodePtr;
}
}
}
NumberList.h:
#include <iostream>
using namespace std;
class NumberList
{
protected:
//Declare a class for the list node.
struct ListNode
{
int i,j;
ListNode *next;
ListNode(int i1, int j1, ListNode *next1=NULL)
{
i=i1;
j=j1;
next=next1;
}
};
ListNode *head;//List head pointer
public:
NumberList(){head=NULL;}
//~NumberList();
void add(int i, int j);
void remove(int i, int j);
void displayList();
};

Needed to add the method call with the structure pointer operator on both sides of the and sign. Instead of:
if (head-> i&&j == x&&y)
Did this:
if (head-> i==x && head->j==y)

Related

How do you create a singly linked list with input in C++

We were tasked with creating a linked list with the following output:
Enter number of nodes: 5
12 4 5 44 45
The linked list:
12 4 5 44 45
I am very confused with linked lists, with my code being the following
#include <iostream>
using namespace std;
struct Node{
int data;
int nodeNumber;
Node *next;
}*nodePtr=NULL,*nodeTemp=NULL,*nodeHead=NULL;
void addNode (int num, int nodeSize);
void displayNode();
int main(){
int size, value;
cout<<"Enter number of Nodes: ";
cin>>size;
for (int i=0; i<size; i++){
cin>>value;
addNode(value,size);
//These are just to check if the data is being stored correctly in the structs
cout<<nodeTemp->data;
cout<<nodePtr->data;
cout<<nodeHead->data;
}
displayNode();
system("pause>0");
}
void addNode(int num, int nodeSize){
int i = 0;
nodePtr = new Node;
nodePtr->data = num;
nodePtr->next = NULL;
if (nodePtr->next == NULL){
nodeHead = nodePtr;
nodeTemp = nodePtr;
nodePtr->next = nodeTemp;
}
else
while(i<nodeSize){
nodeTemp->next = nodeTemp;
}
nodeTemp->next = NULL;
}
void displayNode(){
nodeTemp = new Node;
nodeTemp = nodeHead;
cout<<"The linked list: ";
while(nodeTemp != NULL){
cout<<nodeTemp->data<<" ";
nodeTemp = nodeTemp->next;
}
}
The code however, only outputs the last value inputted. When I checked the data (see line 22,23,24), it seems that the node pointer, temp, and the head always have the same values. I am confused with what my mistakes might be, and any help would be very nice.
Thank you.
You do not have to pass the size variable to the addNode Function. Just take values as much you desire in main funtion and pass them to addNode funtion by looping till the size, then add Nodes to the list as usual.
Your code will look something like this:
#include <iostream>
using namespace std;
struct Node{
int data;
int nodeNumber;
Node *next;
};
Node *nodeHead=NULL;
void addNode (int num);
void displayNode();
int main(){
int size, value;
cout<<"Enter number of Nodes: ";
cin>>size;
for (int i=0; i<size; i++){
cin>>value;
addNode(value);
}
displayNode();
system("pause>0");
}
void addNode(int num){
Node *tail = nodeHead;
Node *nodePtr = new Node;
nodePtr->data = num;
nodePtr->next = NULL;
if (nodeHead == NULL){
nodeHead = nodePtr;
}
else{
while(tail->next != NULL){
tail = tail->next;
}
tail->next = nodePtr;
}
}
void displayNode(){
Node *nodeTemp = new Node;
nodeTemp = nodeHead;
cout<<"The linked list: ";
while(nodeTemp != NULL){
cout<<nodeTemp->data<<" ";
nodeTemp = nodeTemp->next;
}
}
there is no need for size variable while you are inserting a node at the end of the list.
change your function like below:
void addNode(int num){
nodePtr = new Node;
nodePtr->data = num;
nodePtr->next = NULL;
/* if head is null, or list is empty! */
if (nodeHead == NULL){
nodeHead = nodePtr;
}
else{
/* traverse the list to the end and add node at the NULL position */
/* create a chain of nodeHead to nodeTemp */
nodeTemp = nodeHead;
while(nodeTemp-> next != NULL){
nodeTemp = nodeTemp->next;
}
nodeTemp->next = nodePtr;
}
}

can u use head->data as an integer variable, if the "data" is integer type in chained lists?

can u use head->data as an integer variable, if the "data" is integer type in chained lists.
for example, I have a code where I have to transform a simply chained list of integer variables, into 2 lists, one with positive numbers, the other one with negative numbers. I cant find the error in my code...
using namespace std;
struct Node{
int data;
Node* next;
};
Node* head=new Node;
Node* pozitiv=NULL;
Node* negativ=NULL;
Node* newNode(int data)
{
Node* nodNou = new Node();
nodNou -> data = data;
nodNou -> next = NULL;
return nodNou;
}
void Push(Node* &top, int data)
{
Node* nodNou = newNode(data);
nodNou -> next = top;
top = nodNou;
}
void read(){
Node* aux=new Node;
int r,i,v[1000];
cout<<"insert the number of elements in list"<<endl;
cin>>r;
cin>>v[0];
head->data=v[0];
head->next=NULL;
for(i=1;i<r;i++){
cin>>v[i];
aux->data=v[i];
aux->next=head;
head=aux;
aux=new Node;
}
}
write(){
if(head==NULL) return 0;
else{
while(head!=NULL){
cout<<head->data<<"->";
head=head->next;
}
}
cout<<endl<<endl;
}
void stivezlutat(){
Node* aux;
pozitiv=new Node;
pozitiv->next=NULL;
negativ=new Node;
negativ->next=NULL;
while(head!=NULL){
if(head->data >= 0){
Push(pozitiv, head->data);
}
else{
Push(negativ, head->data);
}
head=head->next;
}
cout<<"pozitive list:"<<endl;
while(pozitiv != NULL){
cout<<pozitiv->data<<"->";
pozitiv=pozitiv->next;
}
cout<<endl;
cout<<"negative list:"<<endl;
while(negativ != NULL){
cout<<negativ->data<<"->";
negativ=negativ->next;
}
}
int main()
{
read();
write();
stivezlutat();
}```
Errors in your code:
Required #include directives don't present.
extra "```" exists at the end of code.
No return type is specified for write.
In the function write, return with value is used while no return statement presents at the end of the function, so no return type is valid for that.
The function write breaks the value of head, so the function stivezlutat will see empty list.
Extra nodes are assigned to pozitiv and negativ and they are printed in the funciton stivezlutat.
Fixed code (also indentation is fixed):
#include <iostream>
using namespace std;
struct Node{
int data;
Node* next;
};
Node* head=new Node;
Node* pozitiv=NULL;
Node* negativ=NULL;
Node* newNode(int data)
{
Node* nodNou = new Node();
nodNou -> data = data;
nodNou -> next = NULL;
return nodNou;
}
void Push(Node* &top, int data)
{
Node* nodNou = newNode(data);
nodNou -> next = top;
top = nodNou;
}
void read(){
Node* aux=new Node;
int r,i,v[1000];
cout<<"insert the number of elements in list"<<endl;
cin>>r;
cin>>v[0];
head->data=v[0];
head->next=NULL;
for(i=1;i<r;i++){
cin>>v[i];
aux->data=v[i];
aux->next=head;
head=aux;
aux=new Node;
}
}
void write(){
if(head==NULL) return;
else{
Node* cursor = head;
while(cursor!=NULL){
cout<<cursor->data<<"->";
cursor=cursor->next;
}
}
cout<<endl<<endl;
}
void stivezlutat(){
Node* aux;
pozitiv=NULL;
negativ=NULL;
while(head!=NULL){
if(head->data >= 0){
Push(pozitiv, head->data);
}
else{
Push(negativ, head->data);
}
head=head->next;
}
cout<<"pozitive list:"<<endl;
while(pozitiv != NULL){
cout<<pozitiv->data<<"->";
pozitiv=pozitiv->next;
}
cout<<endl;
cout<<"negative list:"<<endl;
while(negativ != NULL){
cout<<negativ->data<<"->";
negativ=negativ->next;
}
}
int main()
{
read();
write();
stivezlutat();
}

I'm trying to implement a binary tree. My program stops abruptly after a few node insertions. What is going wrong?

I'm just trying out implementation of binary tree. It's not for a college class so I cannot ask a teacher :(
I have tried debugging it with the Codeblocks debugger but I'm still not understanding what is going wrong.
I am using class instead of struct. Currently I have only implemented insertion and inorder traversal functions.
For insertion function, I am checking if the root node is NULL or not. If it is NULL, the newNode becomes equal to the root node. Or else, I find the appropriate parent node and then append the newNode as its child.
And, in the inorder traversal function, is my recursion correct?
Edit: Turns out that I wasn't initializing my Node variables. My code is working after initializing those variables. Thanks for your help!
#include<iostream>
using namespace std;
class Node
{
public:
int data;
Node* left_child;
Node* right_child;
};
Node* root = NULL;
void insertion();
void inorder_travesal(Node*);
int main(){
char ch;
do{
int choice;
cout<<"\nEnter your choice: \n1. Insertion\n2. Inorder Traversal\n : ";
cin>>choice;
switch(choice){
case 1: insertion();
break;
case 2: inorder_travesal(root);
break;
}
cout<<"\nDo you want to continue?: ";
cin>>ch;
}while(ch == 'y');
return 0;
}
void insertion(){
int data;
cout<<"\nEnter data: ";
cin>>data;
Node* newNode = new Node;
newNode->data = data;
if(root == NULL)
{
root = newNode;
return;
}
else
{
Node* temp = root;
while(true){
if(temp->data > newNode->data)
{
if(temp->left_child == NULL)
{
temp->left_child = newNode;
return;
}
else
{
temp = temp->left_child;
}
}
else
{
if(temp->right_child == NULL)
{
temp->right_child = newNode;
return;
}
else
{
temp = temp->right_child;
}
}
}
}
inorder_travesal(root);
}
void inorder_travesal(Node* temp){
if(temp->left_child != NULL){
inorder_travesal(temp->left_child);
}
cout<<temp->data<<" ";
if(temp->right_child != NULL){
inorder_travesal(temp->right_child);
}
}

Linked List issue insert from middle C++

I am new to linked lists, and now I face a problem on how to add the node into the middle of a list. Example like if I got a name list show below and when I add data one by one just like below sequence:
1.andrew
2.eric
3.madness
4.gerik
I want my data "gerik" in "madness" place when it show out. I am able to sort the data infront of "eric" but after "eric" i am not idea. I want my output just like below:
1.andrew
2.eric
3.gerik
4.madness
Below will be my example code, please help me by giving me advise or code sample:
#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
using namespace std;
struct node
{
char f_name[20];
char l_name[20];
char u_id[10];
node *next;
};
node *head;
node *curr;
//prototype
void display();
void add();
void search_name();
void insert_data(node *tempnode);
void insert_before_head(node *tempnode);
void menu(char choice);
char pause;
//function start...
void search_name()
{
char name[20];
curr = head;
cin.ignore(30,'\n');
cout<<"Key In Last Name :"<<endl;
cin.get(name, 20);
cin.ignore(30,'\n');
while((curr->next != NULL) && (strcmp(curr->l_name, name) != 0))
{
curr = curr->next;
}
if(curr != NULL)
{
cout<<"Record Found !"<<endl;
cout<<"First Name"<<setw(16)<<"Last Name"<<setw(16)<<"User ID"<<endl;
cout<<"--------------------------------------------------------------"<<endl;
cout<<curr->f_name<<setw(20)<<curr->l_name<<setw(16)<<curr->u_id<<endl<<endl;
}
else
{
cout<<"No Match !"<<endl;
cout<<"Press 'Enter' To Continue"<<endl;
cin.get(pause = getch());
system("cls");
}
};
void display()
{
curr = head;
if(head != NULL)
{
cout<<"First Name"<<setw(16)<<"Last Name"<<setw(16)<<"User ID"<<endl;
cout<<"--------------------------------------------------------------"<<endl;
while(curr != NULL)
{
cout<<curr->f_name<<setw(20)<<curr->l_name<<setw(16)<<curr->u_id<<endl;
curr = curr->next;
}
}
else
{
cout<<"No Data. File storage Empty!"<<endl;
}
};
void add()
{
node *temp;
temp = new node;
cin.ignore(30, '\n');
cout<<"Key In First Name:"<<endl;
cin.get(temp->f_name, 20);
cin.ignore(30, '\n');
cout<<"Key In Last Name:"<<endl;
cin.get(temp->l_name, 20);
cin.ignore(30, '\n');
cout<<"Key In Your ID:"<<endl;
cin.get(temp->u_id, 10);
insert_data(temp);
};
void insert_data(node *tempnode)
{
node *temp;
if(head == NULL)
{
node *temp;
temp = new node;
temp = head;
tempnode->next = NULL;
head = tempnode;
}
else if(strcmp(tempnode->l_name, head->l_name) < 0)
{
insert_before_head(tempnode);
}
else
{
temp = new node;
curr = head;
while(curr->next != NULL)
{
curr = curr->next;
}
temp = tempnode;
curr->next = tempnode;
tempnode->next = NULL;
}
};
void insert_before_head(node *tempnode)
{
node *temp;
if(head != NULL)
{
temp = new node;
temp = tempnode;
tempnode->next = head;
head = tempnode;
}
};
void menu(int choice)
{
switch (choice)
{
case 1 :
add();
break;
case 2:
display();
break;
case 3:
search_name();
break;
case 4:
cout<<"Exit Program !"<<endl;
break;
default :
cout<<"Error! Program Terminate !"<<endl;
}
};
int main()
{
int choice;
node *temp;
head = NULL;
curr = NULL;
cout << "Data Stack Head And Any Position !" << endl;
system("cls");
do{
cout<<"1. Add Data."<<endl;
cout<<"2. Show Data. "<<endl;
cout<<"3. Search Last Name "<<endl;
cout<<"4. Exit. "<<endl;
cin >>choice;
menu(choice);
}while(choice != 4);
return 0;
}
To sort linked lists you need to use the divide and conquer strategy with merge sort.
In order to insert in the middle you need to create 2 nodes Node slow and Node fast. At first Node slow is head.next, Node fast is head.next.next and you keep moving those 2 by doing slow = slow.next and fast = fast.next.next, until you hit the end with Node fast. If you think about it, fast will be moving twice as fast as Node slow, so in the end Node slow will be in the middle. Then insert after that node.
We want to insert in our list newNode.
Let node X be the node, after which newNode should be inserted to preserve sorting order.
You can rewite your insert_data(...) function like in my example.
I took the code, sugested by WhozCraug and rewrote it to be more evident.
void insert_data(node *newNode)
{
node **pointerToTheNextPtr = &head;
// find position to insert new node
while (*pointerToTheNextPtr && strcmp((*pointerToTheNextPtr)->l_name, newNode->l_name) < 0)
pointerToTheNextPtr = &((*pointerToTheNextPtr)->next);
// here pointerToTheNextPtr stores the pointer to the X->next field
// insert new node between X and *(X->next)
newNode->next = *pointerToTheNextPtr; // set newNode->next = X->next
*pointerToTheNextPtr = newNode; // set X->next = newNode
}

I'm having trouble with cpp code to insert elements in a binary tree

I've tried this way to insert elements in a binary tree in code blocks. The program got compiled but got a run time error and the program stopped running. Could some one please help me out in this issue.
Thanks in advance.
#include <iostream>
#include <cstdlib>
using namespace std;
class bst;
class node
{
public:
int data;
node *lc;
node *rc;
};
class bst
{
public:
node *root;
bst()
{
root = NULL;
}
void search(int, node **, node **);
void insert(int);
void display(node *, int);
};
void bst::search(int item, node **par, node **loc)
{
node *current;
node *ptr;
if(root == NULL)
{
*par = NULL;
*loc = NULL;
return;
}
if(item == root->data)
{
*par = NULL;
*loc = root;
return;
}
if(item < root->data)
current = root->lc;
else
current = root->rc;
ptr = root;
while(current != NULL)
{
if(item == current->data)
{
*par = ptr;
*loc = current;
return;
}
ptr = current;
if(item < current->data)
current = current->lc;
else
current = current->rc;
}
*par = current;
*loc = NULL;
}
void bst::insert(int item)
{
node *parent;
node *location;
node *temp;
search(item, &parent, &location);
temp = new node;
temp->data = item;
temp->lc = NULL;
temp->rc = NULL;
if(item < parent->data)
parent->lc = temp;
else
parent->rc = temp;
}
void bst::display(node *ptr, int level)
{
if(ptr != NULL)
{
display(ptr->rc, level+1);
cout<<"\n";
for(int i=0;i<level;i++)
cout<<" ";
cout<<ptr->data;
display(ptr->lc, level+1);
}
}
int main()
{
int ch, num;
bst b;
while(1)
{
cout<<"1. INSERT ; 2. DISPLAY ; 3. EXIT "<<endl;
cout<<"Enter your choice"<<endl;
cin>>ch;
switch(ch)
{
case 1: cout<<"Enter the number to insert"<<endl;
cin>>num;
b.insert(num);
break;
case 2: b.display(b.root, 1);
break;
case 3: exit(0);
}
}
return 0;
}
In this line search(item, &parent, &location); you are calling the function search with arguments of types int, node** and node**. It in fact expects int, node* and node*. You should change the function declaration to search(int, node**, node**).