I seem to keep get a "Segmentation Error: 11" whenever I run any function(insert and display, unable to tell if delete does it since i can't insert) in the program. I'm not totally sure what it means or where to begin looking to fix it. Any help would be greatly appreciated on where to begin. I understand that it has something to do with the memory and from what I was able to find it could mean that something is taking up too much memory.
#include <iostream>
#include <cstring>
#include <cstdlib>
#include "priority_queue.h"
//#include <heap.h>
using namespace std;
struct node{
int priority;
int info;
struct node* link;
};
class PriorityQueue{
private:
node* front;
public:
void Priority_Queue(){
front = 0;
}
void insert(int item, int priority){
node* temp, *q;
temp = new node;
temp->info = item;
temp->priority = priority;
if(front == 0 || priority < front->priority){
temp ->link = front;
front = temp;
}
else{
q = front;
while(q->link != 0 && q->link->priority <= priority)
q = q->link;
temp->link = q->link;
q->link = temp;
}
}
void del(){
node* temp;
if(front == 0)
cout << "Underflow" << endl;
else{
temp = front;
cout << "Delete item is: " << temp->info << endl;
front = front->link;
free(temp);
}
}
void display(){
node* ptr;
ptr = front;
if(front == 0)
cout << "Queue is empty" << endl;
else{
cout << "Queue is: " << endl;
cout << "Priority Item" << endl;
while(ptr != 0){
cout << ptr->priority << endl;
ptr = ptr->link;
}
}
}
};
int main(){
int choice, item, priority;
PriorityQueue pq;
while(1){
cout << "1. Insert" << endl;
cout << "2. Delete" << endl;
cout << "3. Display" << endl;
cout << "4. Quit" << endl;
cout << "Enter Choice " << endl;
cin >> choice;
switch(choice){
case 1:
cout << "Input the item value to be added into the queue" << endl;
cin >> item;
cout << "Enter its priority " << endl;
cin >> priority;
pq.insert(item, priority);
break;
case 2:
pq.del();
break;
case 3:
pq.display();
break;
case 4:
break;
default:
cout << "That is not an option" << endl;
}
}
//while(choice != 4);
return 0;
}
The problem appears to be the class definition. As WhozCraig points out the name of the presumed constructor is wrong, so it never gets called. The corrected code:
class PriorityQueue {
private:
node* front;
public:
PriorityQueue() : front(nullptr) {
}
};
If you had a look in your debugger you'd probably see that front was never properly initialized. In C++ try and use nullptr to represent a "null pointer". In C use NULL. Using 0 creates a lot of ambiguity even if it "works" for historical reasons.
Related
using namespace std;
void createsqueue();
void insertname();
void insertheight();
void del();
void push();
void display();
struct nodename
{
string name;
float height;
struct nodename *next;
};
nodename *front;
nodename *rear;
void createstack()
{
front = NULL;
rear = NULL;
}
void insertname()
{
while (true)
{
char dec;
nodename *temp;
temp = new nodename;
std::cout << "ENTER YOUR NAME : ";
std::cin >> temp -> name;
std::cout << "ENTER YOUR HEIGHT : ";
std::cin >> temp -> height;
std::cout <<'\n';
temp -> next = NULL;
if(rear == NULL)
{
rear = temp;
front = temp;
}
else
{
rear -> next = temp;
rear = temp;
}
std::cout << "ADD ANOTHER DATA? (Y/N) : ";
std::cin >> dec;
std::cout <<'\n';
if (dec == 'n' || dec == 'N')
{
break;
}
}
}
void del()
{
if(front != NULL)
{
nodename *temp = front;
cout << "The deleted element is: " << temp -> name << endl;
front = front -> next;
delete temp;
}
else
{
cout << "Queue List is empty!\n";
}
}
void display()
{
nodename *temp = front;
while(temp != NULL)
{
std::cout << "--------------------------" << '\n';
std::cout <<"NAME : "<< temp -> name << endl;
std::cout << showpoint << fixed << setprecision(0);
std::cout <<"HEIGHT : " << temp -> height << endl;
std::cout << showpoint << fixed << setprecision(2);
temp = temp -> next;
std::cout << "--------------------------" << '\n';
}
}
int main()
{
int operation;
createstack();
do
{
std::cout << "\tMAIN MENU" << endl;
std::cout << "1 - ENTER NAME : "
<< "\n2 - DELETE PREV DATA : "
<< "\n3 - DISPLAY DATA : "
<< "\n0 - End Program"
<< "\nEnter your operation: ";
cin >> operation;
switch (operation)
{
case 1: insertname();
break;
case 2: del();
break;
case 3: display();
break;
case 0: cout << "Program End";
break;
default:
cout << "Wrong option. Please insert a new operation: ";
}
}
while(operation ! = 0);
return 0;
}
This is the code.
The program Works fine the only problem I have is displaying the name with height in descending order so that the tallest person's info displays first
I have tried multiple ways but nothing seems to work it might be my in-experience in coding since im a newbie and pardon me for any error im just getting started
Modify the code for inserting a new name such that whenever you add a node,you find the correct position for it before inserting in the linked list.
void insertname(){
cin>>h;
nodename* ctr=front;
while(ctr-> height >h){
ctr=ctr->next;
}
nodename* temp =new nodename;
temp->next=ctr->next
ctr->next=temp
temp->height=h; //similarly for name
}
Just find it if the node added is the first node or any other which you have achieved and the above will add nodes in the descending order, which will be displayed as you wanted. So, you can modify it accordingly.
below is my current in-progress code converting a singly linked to a doubly linked list. I haven't touched the delete function yet. I've gotten insert in empty list, end of list, and beginning of list apparently working.
However nodes inserting in the middle seemingly fail to create a link to the previous node. My debugging lines I inserted seem to show both the n->next and n-> prev with the correct memory address, but when I go to reverseprint, any nodes inserted in the middle are missed and the links are gone. Where am I going wrong in regards to this?
Code below:
#include <iostream>
#include <string>
using namespace std;
// define a node for storage and linking
class node {
public:
string name;
node *next;
node *prev;
};
class linkedList {
public:
linkedList() :top(NULL) {}
bool empty() { return top == NULL; }
node *getTop() { return top; }
node *getEnd() { return end; }
void setTop(node *n) { top = n; }
void setEnd(node *p) { end = p; }
void add(string);
int menu();
void remove(string);
~linkedList();
void reversePrint();
friend ostream& operator << (ostream&, const linkedList&); // default output is in-order print.
private:
node *top;
node *end;
};
void main() {
linkedList l;
cout << l.empty() << endl;
int option = 0;
string s;
bool go = true;
while (go) {
option = l.menu();
switch (option) {
case 1: cout << "enter a name: "; cin >> s; l.add(s); break;
case 2: cout << "enter name to be deleted: "; cin >> s; l.remove(s); break;
case 3: cout << l; break;
//case 4: cout << "can not be done with a singly linked list" << endl;
case 4: l.reversePrint(); break;
case 5: cout << "exiting" << endl; go = false; break;
}
}
system("pause");
}
void linkedList::remove(string s) {
bool found = false;
node *curr = getTop(), *prev = NULL;
while (curr != NULL) {
// match found, delete
if (curr->name == s) {
found = true;
// found at top
if (prev == NULL) {
node *temp = getTop();
setTop(curr->next);
delete(temp);
// found in list - not top
}
else {
prev->next = curr->next;
delete(curr);
}
}
// not found, advance pointers
if (!found) {
prev = curr;
curr = curr->next;
}
// found, exit loop
else curr = NULL;
}
if (found)cout << "Deleted " << s << endl;
else cout << s << " Not Found " << endl;
}
void linkedList::add(string s) {
node *n = new node();
n->name = s;
n->next = NULL;
n->prev = NULL;
// take care of empty list case
if (empty()) {
top = n;
end = n;
// take care of node belongs at beginning case
}
else if (getTop()->name > s) {
n->next = getTop();
n->prev = NULL;
setTop(n);
node *temp;
temp = n->next;
temp->prev = n;
// take care of inorder and end insert
}
else {
// insert in order case
node *curr = getTop(), *prev = curr;
while (curr != NULL) {
if (curr->name > s)break;
prev = curr;
curr = curr->next;
}
if (curr != NULL) { // search found insert point
n->next = curr;
cout << n->name << " " << n << " prev " << prev << " " << prev->name << endl;
n->prev = prev;
prev->next = n;
cout << "n->prev is: " << n->prev << " " << n->prev->name << endl;
cout << "n->next is: " << n->next << " " << n->next->name << endl;
}
// take care of end of list insertion
else if (curr == NULL) {// search did not find insert point
prev->next = n;
n->prev = prev;
cout << "n->prev is: " << n->prev << " " << n->prev->name << endl;
setEnd(n);
}
}
}
ostream& operator << (ostream& os, const linkedList& ll) {
//linkedList x = ll; // put this in and the code blows up - why?
node *n = ll.top;
if (n == NULL)cout << "List is empty." << endl;
else
while (n != NULL) {
os << n->name << endl;
os << n << endl;
if (n->next != NULL) {
os << "next is " << n->next << endl;
}
n = n->next;
}
return os;
}
void linkedList::reversePrint() {
node *n = end;
if (n == NULL)cout << "List is empty." << endl;
else
while (n != NULL) {
//cout << n->name << endl;
cout << "memory address of " << n->name << " is " << n << endl;
if (n->prev != NULL) {
cout << "prev is " << n->prev << endl;
}
n = n->prev;
}
return;
}
// return memory to heap
linkedList::~linkedList() {
cout << "~linkedList called." << endl;
node *curr = getTop(), *del;
while (curr != NULL) {
del = curr;
curr = curr->next;
delete(del);
}
}
int linkedList::menu() {
int choice = 0;
while (choice < 1 || choice > 5) {
cout << "\nEnter your choice" << endl;
cout << " 1. Add a name." << endl;
cout << " 2. Delete a name." << endl;
cout << " 3. Show list." << endl;
cout << " 4. Show reverse list. " << endl;
cout << " 5. EXIT " << endl;
cin >> choice;
}
return choice;
}
You are not setting the prev of the current in insertion into middle, just do:
n->next = curr;
curr->prev = n; // <-- this
This is what I have so far, but it's not working. Basically skips to else if(cnode == preposition).
void LinkedList::Delete(Node *PrePosition) {
Node *cnode = head;
Node *pnode = NULL;
while (cnode != NULL) {
if (cnode->value != NULL) {
if (pnode == NULL) {
// if there is not previous node
head = cnode->next;
}
else if (cnode == PrePosition) {
// if there is previous node
cout << endl << "Deleting: " << cnode << endl;
pnode->next = cnode->next;
}
}
else {
// don't delete
pnode = cnode;
}
cnode = cnode->next;
}
}
1: Take the pointer from the previous node and point it to the next one after the one you want to delete
2: Delete the pointer from the previous node to the current node
3: Delete the pointer from the next node to the current node (if it is a doubly-linked list)
Three cases of delete in a singly linked-list:
delete the first node
void delete_first()
{
node *temp=new node;
temp=head;
head=head->next;
delete temp;
}
delete the last node
void delete_last()
{
node *current = new node;
node *previous = new node;
current=head;
while(current->next != NULL)
{
previous = current;
current = current->next;
}
tail = previous; // if you have a Node* tail member in your LinkedList
previous->next = NULL;
delete current;
}
delete at a particular position (your case)
void LinkedList::delete_position(int pos)
{
node *current=new node;
node *previous=new node;
current=head;
for(int i=1; i < pos; i++) //or i = 0; i < pos-1
{
previous=current;
current=current->next;
}
previous->next=current->next;
delete current;
}
^^ from codementor ^^
However if your function signature intends delete_node(Node* nodeToDelete) [PrePosition is not a good name in this case] and you want delete the node passed to the function without knowing its position in the list we can modify delete_position() like so:
void LinkedList::delete_node(Node* nodeToDelete)
{
node *current= head;
node *previous= nullptr;
if (head == nodeToDelete){
head = nodeToDelete->next;
delete nodeToDelete;
return
}//else
while(current != nodeToDelete)
{
previous = current;
current = current->next
}
previous->next = current->next;
delete nodeToDelete;
}
Also in your original code, if it's skipping the line you mentioned, pnode is always null when cnode has a non-null value in it.
Here are the full code
class SportShoe {
private:
struct nodeSport {
int ShoeID;
char BrandShoe[SIZE];
char TypeShoe[SIZE];
char ColourShoe[SIZE];
int SizeShoe;
float PriceShoe;
nodeSport *last;
};
nodeSport *first = NULL;
public:
int MenuSportShoe();
void AddSportShoe();
void DisplaySportShoe();
void DeleteSportShoe();
static void ExitSportShoe();
};
int SportShoe::MenuSportShoe() {
int OptionSportShoe = 0;
cout << endl;
cout << "Please select from the menu:" << endl;
cout << ":: 1 :: Add item to shoe list" << endl;
cout << ":: 2 :: Display shoes list" << endl;
cout << ":: 3 :: Delete item from the list" << endl;
cout << ":: 4 :: Back" << endl;
cout << "=>> ";
cin >> OptionSportShoe;
while (OptionSportShoe == 1){
AddSportShoe();
}
while (OptionSportShoe == 2){
DisplaySportShoe();
}
while (OptionSportShoe == 3){
DeleteSportShoe();
}
while (OptionSportShoe == 4){
ExitSportShoe();
}
return 0;
}
void SportShoe::AddSportShoe() {
nodeSport *tempShoe1, *tempShoe2;
tempShoe1 = new nodeSport;
cout << "Please enter the Shoe ID : (eg. 43210) " << endl;
cout << "=>> ";
cin >> tempShoe1->ShoeID;
cout << "Please enter the Shoe Brand: (eg. Adidas) " << endl;
cout << "=>> ";
cin.sync();
cin.getline(tempShoe1->BrandShoe,SIZE);
cout << "Please enter the Shoe Type : (eg. Running) " << endl;
cout << "=>> ";
cin.sync();
cin.getline(tempShoe1->TypeShoe,SIZE);
cout << "What is the Shoe Colour : (eg. Grey) " << endl;
cout << "=>> ";
cin.sync();
cin.getline(tempShoe1->ColourShoe,SIZE);
cout << "Please enter Shoe Size : (eg. 9) " << endl;
cout << "=>> ";
cin >> tempShoe1->SizeShoe;
cout << "Please enter the price of the Shoe : (eg. RM123.45) " << endl;
cout << "=>> RM ";
cin >> tempShoe1->PriceShoe;
tempShoe1->last = NULL;
if (first == NULL)
first = tempShoe1;
else
{
tempShoe2 = first;
while (tempShoe2->last != NULL)
tempShoe2 = tempShoe2->last;
tempShoe2->last = tempShoe1;
}
system("PAUSE");
MenuSportShoe();
}
void SportShoe::DisplaySportShoe() {
nodeSport *tempShoe1;
tempShoe1 = first;
while(tempShoe1){
cout << "ID : " << tempShoe1->ShoeID << endl;
cout << "Brand : " << tempShoe1->BrandShoe << endl;
cout << "Type : " << tempShoe1->TypeShoe << endl;
cout << "Colour : " << tempShoe1->ColourShoe << endl;
cout << "Size : " << tempShoe1->SizeShoe << endl;
cout << "Price : " << tempShoe1->PriceShoe << endl;
cout << endl;
tempShoe1 = tempShoe1->last;
}
system("PAUSE");
MenuSportShoe();
}
void SportShoe::DeleteSportShoe(){
nodeSport *tempShoe1, *tempShoe2;
int DataShoe;
tempShoe2 = tempShoe1 = first;
if(tempShoe1 == NULL)
{
cout << "\nList is empty!" << endl;
system("PAUSE");
MenuSportShoe();
}
while(tempShoe1 != NULL)
{
cout << "\nEnter the Shoes ID to be deleted: (eg. 123) ";
cin >> DataShoe;
tempShoe2 = tempShoe1;
tempShoe1 = tempShoe1->last;
if(DataShoe == tempShoe1-> ShoeID){
if(tempShoe1 == first) {
first = first->last;
cout << "\nData deleted ";
}
else{
tempShoe2->last = tempShoe1->last;
if(tempShoe1->last == NULL){
tempShoe2 = tempShoe2;
}
cout << "\nData deleted ";
}
delete(tempShoe1);
system("PAUSE");
MenuSportShoe();
}
else{
cout << "\nRecord not Found!!!" << endl;
system("PAUSE");
MenuSportShoe();
}
}
}
void SportShoe::ExitSportShoe(){
int sepatu;
cout << endl;
cout << "Please choose the option below."<<endl;
cout << ":: 1 :: Sport Shoe." << endl;
cout << ":: 2 :: Ladies High Heel." << endl;
cout << ":: 3 :: Exit" << endl;
cout << "=>> ";
cin >> sepatu;
while(sepatu == 1){
SportShoe listShoe;
listShoe.MenuSportShoe();
}
while(sepatu == 2){
HighHeel listShoe;
listShoe.MenuHighHeel();
}
while(sepatu == 3){
cout << "Thank you. Till we meet again."<< endl;
exit(1);
}
}
main() {
cout << "Hello! Welcome to MySepatu Online Shop administrator."<< endl;
cout << endl;
SportShoe::ExitSportShoe();
HighHeel::ExitHighHeel();
return 0;
}
public class linkedList {
int count = 0;
class Node {
int element;
Node next;
Node(int element) {
this.element = element;
}
}
Node head = null;
Node tail = null;
public void addNode(int Object) {
Node newNode = new Node(Object);
if (head == null) {
head = tail = newNode;
} else {
tail.next = newNode;
tail = newNode;
}
}
public void Display() {
Node current = head;
while (current!=null) {
System.out.println(current.element);
count ++;
current = current.next;
}
}
public void Length() {
System.out.println(count);
}
public void Remove(int node) {
Node curr = head;
while (curr!=null) { // looping the nodes
if (curr.element == node ) {
curr.element = curr.next.element;
curr = curr.next;
// To fix the Duplicates
while (curr!= tail) {
curr.element = curr.next.element;
curr = curr.next;
}
RemoveEnd();
break;
}
curr = curr.next;
}
}
public void RemoveEnd() {
Node current3 = head;
while (current3.next != tail) {
current3 = current3.next;
}
tail = current3;
tail.next = null;
}
}
I'm using a class within a class and I'm getting errors, I think it's a linking problem. I get "undefined reference to 'Node::setlink()', 'Node::getlink()', and etc. It's all the node functions I used in linked_list.cpp that are the problem.
For example, linked_list.cpp:(.text+0x9de): undefined reference to
`Node::getlink()'
Linked_list.cpp
#include "linked_list.hpp"
#include "node.hpp"
#include <iomanip>
#include <iostream>
using namespace std;
//default constructor
Linked_list::Linked_list(void)
{
head = new Node();
tail = new Node();
head->setlink(NULL);
tail->setlink(NULL);
cnt = 0;
}
//constructor
Linked_list::Linked_list(data x)
{
head = new Node();
tail = new Node();
Node *newnode = new Node(x);
head->setlink(newnode);
newnode->setlink(tail);
cnt++;
}
//class function
void Linked_list::insert_node(data x)
{
Node *newNode = new Node(x);
Node *prev = new Node();
Node *curr = new Node();
if (head == NULL)
{
newNode->setlink(tail);
head->setlink(newNode);
}
else if (head != NULL)
{
prev->setlink(head);
curr->setlink(head->getlink());
while(curr->getlink() != NULL || newNode->getupc() <= curr->getupc())
{
prev->setlink(curr);
curr->setlink(curr->getlink());
}
prev->setlink(newNode);
newNode->setlink(curr);
}
cnt++;
}
//Class function
void Linked_list::delete_node(int u)
{
char choice;
data temp;
Node *newNode = new Node();
Node *prev = new Node();
Node *curr = new Node();
if (head == NULL)
{
delete newNode;
delete prev;
delete curr;
}
else if (head != NULL)
{
prev->setlink(head);
curr->setlink(head->getlink());
while (curr->getlink() != NULL || curr->getupc() != u )
{
prev->setlink(curr);
curr->setlink(curr->getlink());
}
temp = curr->get_structure();
cout << temp.UPC << setw(15) << temp.desc << setw(15) << "$" << temp.cost << setw(15) << "Aisle: " << temp.aisle << endl;
prev->setlink(curr->getlink());
cout << "Are you sure you want to delete?\n";
cin >> choice;
if (choice == 'y' || choice == 'Y')
{
delete curr;
cnt--;
}
else
{
choice = 'n';
}
}
}
//Class function
void Linked_list::traverse()
{
data temp;
Node *curr = new Node();
if (head == NULL)
{
delete curr;
cout << "The list is empty!\n";
}
else
{
curr->setlink(head->getlink());
while(curr->getlink() != NULL)
{
temp = curr->get_structure();
cout << temp.UPC << setw(15) << temp.desc << setw(15) << "$" << temp.cost << setw(15) << "Aisle: " << temp.aisle << endl;
}
}
}
void Linked_list::retrieve_node(int u)
{
data temp;
Node *x;
x = new Node();
if (head == NULL)
{
delete x;
}
else if (head != NULL)
{
x->setlink(head->getlink());
while (x->getlink() != NULL || x->getupc() != u)
{
x->setlink(x->getlink());
}
temp = x->get_structure();
cout << temp.UPC << setw(15) << temp.desc << setw(15) << "$" << temp.cost << setw(15) << "Aisle: " << temp.aisle << endl;
}
}
void Linked_list::check_empty()
{
if (head != NULL)
{
cout << "The list is empty.\n";
}
else
{
cout << "The list is not empty.\n";
}
}
linked_list.hpp
#include "node.hpp"
#ifndef linked_list_hpp
#define linked_list_hpp
class Linked_list
{
Node *head;
Node *tail;
int cnt;
public:
//default constructor creates empty linked list
Linked_list(void);
//Constructor that creates first node with values
Linked_list(data x);
//Inserts node at correct spot
void insert_node(data x);
//deletes specific node
void delete_node(int u);
//goes through whole list and prints out
void traverse(void);
//returns specific node
void retrieve_node(int u);
//checks if list is empty
void check_empty();
return_number();
};
#endif
node.hpp
#ifndef node_hpp
#define node_hpp
#include "node.hpp"
#include <string>
using namespace std;
struct data
{
int UPC;
string desc;
int quantity;
double cost;
int aisle;
};
class Node
{
data item;
Node *link;
public:
Node(void);
Node(data x);
void setlink(Node *ptr);
Node* getlink();
int getupc();
data get_structure();
bool compare_item(string i);
double processdata();
};
#endif
node.cpp
#include "node.hpp"
Node::Node(void)
{
link = NULL;
}
Node::Node(data x)
{
item = x;
}
void Node::setlink(Node *ptr)
{
link = ptr;
}
Node* Node::getlink()
{
return link;
}
int Node::getupc()
{
return item.UPC;
}
data Node::get_structure()
{
return item;
}
bool Node::compare_item(string i)
{
if(i==item.desc)
{
return true;
}
else
{
return false;
}
}
double Node::processdata()
{
return item.cost*item.quantity;
}
main function
#include <iostream>
#include "node.cpp"
#include "linked_list.cpp"
using namespace std;
void fromfile(Linked_list &x);
void tofile(Linked_list &x);
int main(void)
{
Linked_list ll;
int x, y;
data a;
do
{
cout << "1.Add a grocery item\n" ;
cout << "2.Delete an item\n";
cout << "3.Retrieve an item\n";
cout << "4.Traverse the list forwards and print out all of the items\n";
cout << "5. Exit the program.\n";
cin >> x;
switch(x)
{
case 1:
cout << "Enter UPC code\n";
cin >> a.UPC;
cout << "Enter description(name of item)\n";
cin >> a.desc;
cout << "Enter quantity\n";
cin >> a.quantity;
cout << "Enter cost\n";
cin >> a.cost;
cout << "Enter aisle\n";
cin >>a.aisle;
ll.insert_node(a);
case 2:
cout << "Enter UPC of item you'd like to delete.\n";
cin >> y;
ll.delete_node(y);
case 3:
cout << "Enter UPC code.\n";
cin >> y;
ll.retrieve_node(y);
case 4:
ll.traverse();
case 5:
cout << "Bye!\n";
default:
cout << "Wrong choice, try again!\n";
}
}while (x != 5);
return 0;
}
Please help me out, this is due in 2 hours. I think I got it running somehow for a while and after the code performs in main, it just stop creating output after it reaches a linked_list function. Then, I can't enter anything afterwards.
The only thing not compiling is the linked_list.cpp, and I get a winmain error as well.
I'm still new to programming. I just wanted to ask how do I to do linear search using pointers. I wanted to make a book management program and i have made a program with pointers written.
This is the example of how i want it.
This is the coding
#include <iostream>
#define MAX 5
using namespace std;
struct record
{
int id;//stores id
float price;//store price
int qty;//stores quantity
record* next;//reference to the next node
};
record* head;//create empty record
record* tail;//the end of the record
void push(record *& head, record *&tail, int id, float price, int qty)
{
if (head == NULL)
{
record* r = new record;
r->id = id;
r->price = price;
r->qty = qty;
r->next = NULL;//end of the list
head = r;
tail = r;
}
else if (head != NULL && (MAX - 1))
{
record* r = new record;
r->id = id;
r->price = price;
r->qty = qty;
r->next = head;
head = r;
}
}
int pop(record *&head, record *& tail)
{
if (head == NULL)
{
cout << "No record in memory" << endl;
}
else if (head == tail)
{
cout << "The record "<<"ID: " << head->id << "\nPrice: " << head->price << "\nQuantity: " << head->qty << "\n" << "was deleted" << endl; //CORRECTION HERE
}
else
{
record* delptr = new record;
delptr = head;
head = head->next;
cout << "The record " << delptr->id << ", " << delptr->price << ", " << delptr->qty << " was deleted" << endl; //CORRECTION HERE
delete delptr;
}
return 0;
}
void display(record *&head)
{
record* temp = new record; //CORRECTION HERE
temp = head;
if (temp == NULL)
{
cout << "No record in memory" << endl;
}
else
{
cout << "Record : " << endl;
while (temp != NULL)
{
cout <<"\nID: "<< temp->id << "\nPrice: " << temp->price << "\nQuantity: " << temp->qty <<"\n"<< endl; //CORRECTION HERE
temp = temp->next;
}
}
}
int LinearSearch(record *&head) {
}
char menu()
{
char choice;
cout << "\t::MENU::\n" << endl;
cout << "1. Add new record\n" << endl;
cout << "2. Delete record\n" << endl;
cout << "3. Show record\n" << endl;
cout << "4. Quit\n" << endl;
cout << "-----------------------\n" << endl;
cout << "\nEnter selection : " << endl;
cin >> choice;
return choice;
}
int main()
{
record* head;
record* tail;
head = NULL;
tail = NULL;
char choice;
do
{
cout << "---------------------- - \n" << endl;
choice = menu();
switch (choice) { //CORRECTION HERE
case '1':
int id, qty;
float price;
cout << "Enter ID:";
cin >> id; // Please correct yourself here, what is r here, r is not declared anywhere
cout << "\nEnter Price: ";
cin >> price;
cout << "\nEnter Quantity: ";
cin >> qty;
push(head, tail, id, price, qty);
break;
case '2':
pop(head, tail);
break;
case'3':
display(head);
break;
default:
cout << "Quiting...\n";
}
} while (choice != '4');
return 0;
}
How do I write linear search of pointer code for this coding? I tried finding examples throughout the web and when i execute it, it didn't work so i just leave it blank.
Well, I saw you have a list and you are dealing with pointers.
If you want to do linear search in a record id, for example, you can do it like this:
record *aux = head;
while(aux != NULL){
if(aux->id == id_you_want_to_find){
printf("I found it\n");
}
aux = aux->next;
}
you usually use object.attribute to access the attributes of common objects, but when you have a pointer to an object, you must do pointerToObject->attribute.
You can write one if you want but there is no need to when there already exists libraries that do this for you. Since you are using a list structure I show this using a simple std::list. You could also change this to a std::vector and just do a simple for loop iteration using index notation since the speed of search through them is constant as opposed to linear. Here is one method of doing a search through a list linear.
#include <list>
record* searchRecords( std::list<record>& records, int id ) {
if ( records.empty() ) {
std::ostringstream strStream;
strStream << __FUNCTION__ << " Invalid list of records: list is empty.";
throw ExceptionHandler( strStream ); // Not Written, but what should be done instead of returning.
return nullptr;
}
std::list<record>::iterator it = records.begin();
while ( it != records.end() ) {
if ( it->id == id ) {
return (&(*it));
}
++it;
}
std::ostringstream strStream;
strStream << __FUNCTION__ << " No entry found in search with ID{" << id << "}.";
Logger::log( strStream, Logger::LOGGER_INFO ); // Not implemented here same as above for ExceptionHandler
return nullptr;
}
Since linked lists are not associative they Must be traversed from beginning to end for every entry N in the list to either insert, find or delete. The time complexity here is linear.
If you want faster time insertion time with large lists you can use <multiset> if there may be duplicate items or <set> if every known item is unique. These have instant insertion. If you want constant search and don't care about insertion time then <vector> is what you would want.
The normal answer would be: don't write a linear search yourself, it's called std::find_if. However, C++ expects that your datastructure exposes iterators. An iterator refers to a record (or the end of your list). You get the actual record by calling operator* on the record, and you get the next record by calling operator++.
Yes, this is similar to pointers. That's intentional; pointers are iterators for contiguous arrays. That means you can call std::find_if on an array. But since you chose to implement a linked list instead of an array, you'd' need to implement your own iterator class.