Printing the Circular linked list - c++

#include <iostream>
#include <cstdlib>
using namespace std;
struct node
{
int data;
struct node* link;
};
struct node* front;
struct node* rear;
void insert()
{
struct node*temp;
temp = (struct node*)malloc(sizeof(struct node));
cin >> temp->data;
if (front == NULL)
{
front = rear = temp;
}
else
{
rear->link = temp;
rear = rear->link;
}
rear->link = front;
}
void del()
{
struct node* temp;
temp = front;
if (front == NULL)
cout << "Underflow";
else
{
front = front->link;
free(temp);
}
rear->link = front;
}
void disp()
{
struct node* temp;
temp = front;
if (front == NULL)
cout << "Empty";
else
{
do
{
cout << temp->data << "->";
temp = temp->link;
} while (temp != front);
}
rear->link = front;
}
int main()
{
int n;
bool run = true;
while (run)
{
cin >> n;
switch (n)
{
case 1:
insert();
break;
case 2:
del();
break;
case 3:
disp();
break;
case 4:
run = false;
break;
}
}
return 0;
}
I am new to the concept.I wrote a code for insertion deletion and display of elements using queue implementing the concept of linked list..The program is working fine without any errors . But when the output is displayed . I need to display the output along with the first element I inserted..E.g: My input is
1
2
1
3
1
4
3
The output is 2->3->4->
but the output I need is 2->3->4->2->
I want to see the first element again at the last

All you have to do is just adding a single line after the do-while loop as follows:
do
{
cout << temp->data << "->";
temp = temp->link;
} while (temp != front);
cout<< front->data << "->";
assuming front is the head of your linked-list. Now I've a question for you, what you gonna do if there is a single entry? Since it is going to be displayed twice.

Simple enough, change this
do
{
cout<<temp->data<<"->";
temp=temp->link;
}
while(temp!=front);
to this
int first = temp->data;
do
{
cout<<temp->data<<"->";
temp=temp->link;
}
while(temp!=front);
cout<<first<<"->"; // print first element again

Related

modify the linked list main function code in which user will input the index and data of the node with proper messages

I have a link list in which user will input the index and data of the node with proper messages....
it is a very simple task i know but i am so confuse how to do it .
all i want is that you edit my code so that user can enter which index he/she want to enter data and also he/she is able to enter his/her data..
I'll be very great full if some one reply .
#include <iostream>
using namespace std;
class Node {
public:
double data; // data
Node* next; // pointer to next
};
class List {
public:
List(void) { head = NULL; } // constructor
~List(void); // destructor
bool IsEmpty() { return head == NULL; }
Node* InsertNode(int index, double x);
int FindNode(double x);
int DeleteNode(double x);
void DisplayList(void);
private:
Node* head;
};
Node* List::InsertNode(int index, double x)
{
if (index < 0)
return NULL;
int currIndex = 1;
Node* currNode = head;
while (currNode && index > currIndex) {
//Try to locate index'th node. If it doesn't exist, return NULL
currNode = currNode->next;
currIndex++;
}
if (index > 0 && currNode == NULL)
return NULL;
Node* newNode = new Node;
newNode->data = x;
if (index == 0) {
newNode->next = head;
head = newNode;
}
else {
newNode->next = currNode->next;
currNode->next = newNode;
}
return newNode;
}
int List::FindNode(double x)
{
Node* currNode = head;
int currIndex = 1;
while (currNode && currNode->data != x) {
currNode = currNode->next;
currIndex++;
}
if (currNode)
return currIndex;
return 0;
}
int List::DeleteNode(double x)
{
Node* prevNode = NULL;
Node* currNode = head;
int currIndex = 1;
while (currNode && currNode->data != x) {
prevNode = currNode;
currNode = currNode->next;
currIndex++;
}
if (currNode) {
if (prevNode) {
prevNode->next = currNode->next;
delete currNode;
}
else {
head = currNode->next;
delete currNode;
}
return currIndex;
}
return 0;
}
void List::DisplayList()
{
int num = 0;
Node* currNode = head;
while (currNode != NULL) {
cout << currNode->data << endl;
currNode = currNode->next;
num++;
}
cout << "Number of nodes in the list: " << num << endl;
}
List::~List(void)
{
Node* currNode = head;
Node* nextNode = NULL;
while (currNode != NULL) {
nextNode = currNode->next;
delete currNode; // destroy the current node
currNode = nextNode;
}
}
int main(void)
{
List list;
list.InsertNode(0, 7.0); // successful
list.InsertNode(1, 5.0); // successful
list.InsertNode(-1, 5.0); // unsuccessful
list.InsertNode(0, 6.0); // successful
list.InsertNode(8, 4.0); // unsuccessful
// print all the elements
list.DisplayList();
if (list.FindNode(5.0) > 0)
cout << "5.0 found" << endl;
else
cout << "5.0 not found" << endl;
if (list.FindNode(4.5) > 0)
cout << "4.5 found" << endl;
else
cout << "4.5 not found" << endl;
list.DeleteNode(7.0);
list.DisplayList();
return 0;
}
Just read in the input and call the method on the list object. What did you find so confusing about it?
Also, try to get out of the habit of using namespace std! Append this code to the main function.
int index;
double data;
std::cout << "Enter the index: ";
std::cin >> index;
std::cout << "Enter data: ";
std::cin >> data;
list.InsertNode(index, data);
list.DisplayList();
Declare temporary variables index and data to hold the input from the console.
Print to the console asking the user to enter the index and data using std::cout , which is at the position at which the node is to be entered. std::cin can be used to read input from the console and store it in a variable
The nodes of your linked list contain a data field of type double which is the actual data of your linked list. Using your list object, you call the InsertNode() method along with this index and data.
Don't worry it a very simple task
1:- firstly you should give values in particulate index
2:- ten just fetch it from the particular index
for further information you can contact

How to remove a certain node from a linked list by the data its holding?

We are suppose to enter a string, and then find where the string is in the linked list and remove that node
when i insert to the front of the list, so i enter data values a, b, c , d, when i print it it comes up as d,c,b,a. Now i insert to the rear of it, entering f and g, and the list now looks, d,c,b,a,f,g. I want to remove f but it just use the remove function it does not and still output the same list
using namespace std;
struct node {
string data;
node* next;
};
node* addFront(node* s);
node* addRear(node* s);
void remove(node* head, string abc);
void print(node* head);
int main() {
node* head = NULL;
cout << "Enter 5 data strings\n";
cout << "This will be inserted from the back\n";
for (int i = 0; i < 5; i++) {
head = addFront(head);
}
print(head);
cout << "Enter 3 strings and this will be inserted from the back of the orignal string\n";
for (int i = 0; i < 3; i++) {
head = addRear(head);
}
print(head);
cout << "Removing the head node\n";
string n;
cout << "Enter a string to remove\n";
cin >> n;
remove(head, n);
print(head);
}
node* addFront(node* s)
{
node* person = new node;
cin >> person->data;
person->next = s;
s = person;
return s;
}
node *addRear(node*s ) {
node* person = new node;
cin >> person->data;
person->next = NULL;
if (s == NULL) {
return person;
}
else {
node* last = s;
while (last->next != NULL) {
last = last->next;
}
last->next = person;
}
return s;
}
void remove(node* head, string a) {
node* previous = NULL;
node* current = head;
if (current == NULL) {
cout << "Value cannot be found\n";
return;
}
else {
while (previous != NULL) {
if (current->data == a) {
previous->next = current->next;
delete current;
break;
}
current = current->next;
}
}
}
void print(node * head)
{
node* temp = head;
while (temp != NULL) // don't access ->next
{
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
In remove function, previous is most certainly NULL when you hit that while loop.
Perhaps consider a do-while loop instead (with better handling of previous).
You may be better off handling the first node in a different manner since the holder of its previous is essentially the root pointer.

Output of c++ program not coming as expected

I have made a C++ program for a binary tree. But the terminal is not asking the statement for inputting the direction for where the elements are to be placed.
Also when I replace the statement from " node *temp = new node " to "node *temp=NULL" the program stops working .
#include <iostream>
#include <cstring>
using namespace std;
class node {
int data;
node * left;
node * right;
public:
node * level_order(node * first);
node * create_bt(node * first);
void display(node * first);
};
//node *first=NULL;
node * node::create_bt(node * first) {
node * temp = new node;
int ele;
//char dir;
cout << "\n Enter data ";
cin >> ele;
temp->data = ele;
temp->left = NULL;
temp->right = NULL;
if (first == NULL) {
temp = first;
return first;
} else {
char dir[20];
cout << "\n Enter the direction ";
cin >> dir;
node * cur = first;
int j = 0;
while (dir[j] != '\0') {
if (dir[j] == 'l') {
cur = cur->left;
}
if (dir[j] == 'r') {
cur = cur->right;
}
j++;
}
cur = temp;
return first;
}
}
void node::display(node * first) {
if (first == NULL)
return;
cout << "\n " << first->data;
display(first->left);
display(first->right);
}
int main() {
int n;
node s;
node * first = NULL;
cout << "\n No of elements ";
cin >> n;
for (int i = 0; i < n; i++) {
first = s.create_bt(first);
}
s.display(first);
return 0;
}
first=s.create_bt(first); does not changes state, from NULL to 'l' or 'r'. You have to change that.
node*node::create_bt(node *first)
{
node *temp=new node;
int ele;
//char dir;
cout<<"\n Enter data ";
cin>>ele;
temp->data=ele;
temp->left=NULL;
temp->right=NULL;
char dir[20];
cout<<"\n Enter the direction ";
cin>>dir;
if(first==NULL)
{
temp=first;
return first;
}
else
{
node*cur=first;
int j=0;
while(dir[j]!='\0')
{
if(dir[j]=='l')
{
cur=cur->left;
}
if(dir[j]=='r')
{
cur=cur->right;
}
j++;
}
cur=temp;
return first;
}
}
I believe you re looking something like this. This is a basic binary tree, i had to make a basic one in order to understand how it works and how it chooses left and right. I make a class inside a class, in order to have access to my data members (node class, int data, *left , *right) and have them at the same time protected, all-in-one. As you can see "newnode" just creates a node and NULL s the pointers. Thats it. "Find" searches and finds a node with a current key, and returns it when exits. All the rest, i guess, you can understand them, as they are prety much the same with your code. The only thing you have to do is to define, when you want to direct the node you want. REMINDER: You have to find a way to utilize it, so the leafs will not end far-left or far-right.("Enter the direction"). I hope i helped you understand.
#include <iostream>
#include <conio.h>
using namespace std;
class mybTree {
class node {
public:
int data;
node * left;
node *right;
};
node *root;
node *newnode(int num){
node *newnode1;
newnode1 = new (nothrow) node;
newnode1->data = num;
newnode1->left = NULL;
newnode1->right = NULL;
return newnode1;
}
public:
node *find (int key) {
node *current;
current = root;
while (current->data !=key){
if (key<current->data){
current = current->left;
} else {
current = current->right;
}
if (current == NULL){
return NULL;
}
}
return NULL;
}
void display (node *ptr);
void display_tree();
bool insert(int num);
void post_order_delete(node *ptr);
mybTree();
~mybTree();
};
int main(){
char ch = ' ';
int a;
mybTree mybTree1;
while (ch !='0'){
cout << "0->Exit"<<endl<< "1-> add"<<endl<< "2-> find" <<endl<<"3-> Show me the tree\n";
ch = getch();
switch (ch) {
case '0':
break;
case '1':
cout << "number";
cin >> a;
if (!mybTree1.insert(a)){
cout << "Not enough memory" << endl;
}
break;
case '2' :
cout << "Number:" ;
cin >> a;
if (mybTree1.find(a)!=NULL) {
cout << "Found" << endl;
} else {
cout << "Not existed" << endl;
}
break;
case '3':
mybTree1.display_tree();
cout<<endl;
break;
default:
cout << "Wrong Message";
break;
}
}
return 0;
}
void mybTree::display(node *ptr) {
if (ptr == NULL){
return;
}
display(ptr->left);
cout << ptr->data<<endl;
display(ptr->right);
}
void mybTree::display_tree() {
//Displays the Tree
display(root);
}
bool mybTree::insert(int num) {
//It inserts a node. Desides left or right.
node *next,*current,*ptr;
int isleft;
next = current = root;
ptr = newnode(num);
if (ptr == NULL) {
return false;
}
if (root == NULL) {
root = ptr;
return true;
}
while (1){
if (num < current->data){
next = current->left;
isleft = 1;
} else {
next = current->right;
isleft = 0;
}
if (next == NULL){
if (isleft){
current->left = ptr;
} else {
current->right = ptr;
}
return true;
}
current=next;
}
return false;
}
void mybTree::post_order_delete(node *ptr) {
//deletes the node. Usefull for destructor
if (ptr == NULL){
return;
}
post_order_delete(ptr->left);
post_order_delete(ptr->right);
cout << ptr->data;
delete ptr;
}
mybTree::mybTree() {
//Constructor
root = NULL;
}
mybTree::~mybTree() {
//Destructor
post_order_delete(root);
root = NULL;
}

Access violation error while creating linked list

Trying to create Lined List. I am having problem in the deleteNode function created in LinkedList.cpp file. Experiencing given error
Unhandled exception at 0x00D04C3C in LinkedList.exe: 0xC0000005:
Access violation reading location 0x00000004.
previous->link = temp->link;
LinkedList.h file
class Node
{
public:
int data;
Node *link;
};
class LList
{
private:
Node *Head, *Tail;
//void recursiveTraverse(Node *);
public:
LList();
~LList();
void create();
Node *getNode();
void append(Node *);
void insert(Node *, int);
void rtraverse();
void deleteNode(int);
void display();
};
LinkedList.cpp
#include "stdafx.h"
#include "LinkedList.h"
#include <iostream>
using namespace std;
LList::LList()
{
Head = nullptr; Tail = nullptr;
}
LList::~LList()
{
Node *Temp;
while (Head != nullptr)
{
Temp = Head;
Head = Head->link;
delete Temp;
}
}
void LList::create()
{
char choice;
Node *newNode = nullptr;
while (5)
{
cout << "Enter Data in the List (Enter N to cancel) ";
cin >> choice;
if (choice == 'n' || choice == 'N')
{
break;
}
newNode = getNode();
append(newNode);
}
}
Node *LList::getNode()
{
Node *temp = new Node;
//cout << "Enter Data in the List";
cin >> temp->data;
temp->link = nullptr;
return temp;
}
void LList::append(Node *temp)
{
if (Head == nullptr)
{
Head = temp;
Tail = temp;
}
else
{
Tail->link = temp;
Tail = temp;
}
}
void LList::display()
{
Node *temp = Head;
if (temp == nullptr)
{
cout << "No Item in the List" << endl;
}
else
{
while (temp != nullptr)
{
cout << temp->data << "\t";
temp = temp->link;
}
cout << endl;
}
}
void LList::insert(Node *newNode, int position)
{
int count = 0; Node *temp, *previous = nullptr;
temp = Head;
if (temp == nullptr)
{
Head = newNode;
Tail = newNode;
}
else
{
while (temp == nullptr || count < position)
{
count++;
previous = temp;
temp = temp->link;
}
previous->link = newNode;
newNode->link = temp;
}
}
void LList::deleteNode(int position)
{
int count = 1; Node * temp, *previous = nullptr;
temp = Head;
if (temp == nullptr)
{
cout << "No Data to delete." << endl;
}
else
{
while (count <= position + 1)
{
if (position == count + 1)
{
count++;
previous = temp;
previous->link = temp->link;
}
else if (count == position + 1)
{
count++;
previous->link = temp->link;
}
count++;
temp = temp->link;
}
}
}
Main.cpp goes here
I see multiple things wrong here, any one of which could be causing your problem. If they don't fix it I could take another look if someone else doesn't get to it first.
First and foremost, your if statements in your delete function will always execute. Because you are assigning instead of checking for equality, ie '=' instead of '=='. This alone may fix the issue.
The other thing that jumps out of the page is that you are obviously dynamically allocating each node, and your delete function should be delete'ing the memory once you are done with it.
Fix those two first and then see where you are at.
Looks like temp cannot be a nullpointer at the line giving an error, but previous might be.
Important: Note that the line
else if (count = position + 1)
Is actually an assignment. You probably meant
else if (count == position + 1)
The same goes for the if statement before that.
Cheers!

Cannot Insert into Ordered Linked List

I am writing a three file C++ program for my class. This program is ordered linked list. The program compiles but crashes when I attempt to insert (Run the program, select choice press enter, type an int to insert and press enter). Any help would be greatly appreciated.
Driver File:
#include "SortedLinkedList.h"
#include <iostream>
using namespace std;
int displayMenu();
void proccessChoice(int, SortedLinkedList&);
int main()
{
SortedLinkedList sSList;
int choice = displayMenu();
do
{
if (choice != 3)
{
proccessChoice(choice, sSList);
}
} while (choice != 3);
return 0;
}
void proccessChoice(int input, SortedLinkedList& l)
{
switch(input)
{
case 1:
int num;
cout << "Please enter a int: ";
cin >> num;
l.addItem(num);
break;
case 2:
l.popFirst();
break;
}
}
int displayMenu()
{
int choice;
cout << "menu" << endl;
cout << "===========" << endl;
cout << "1. add an int" << endl;
cout << "2. Show Sorted Linked List" << endl;
cout << "3. Exit" << endl;
cin >> choice;
cin.ignore();
return choice;
}
Declaration File:
struct sslNode
{
sslNode* next;
int item;
};
class SortedLinkedList
{
private:
sslNode* head;
bool isEmpty ();
public:
SortedLinkedList();
~SortedLinkedList();
void addItem(int);
int popFirst();
};
Implementation File:
#include <iostream>
using namespace std;
#include "SortedLinkedList.h"
SortedLinkedList::SortedLinkedList()
{
head = NULL;
}
SortedLinkedList::~SortedLinkedList()
{
sslNode *temp, *nextLink;
nextLink = head;
while(nextLink != NULL)
{
temp = nextLink->next;
delete nextLink;
nextLink = temp;
}
}
bool SortedLinkedList::isEmpty()
{
return (head == NULL);
}
void SortedLinkedList::addItem(int itemToInsert)
{
sslNode* cur;
sslNode* prev;
sslNode* newNode = new sslNode();
newNode->item = itemToInsert;
newNode->next = NULL;
cur = head;
prev = NULL;
bool moreToSearch (cur != NULL);
while (moreToSearch) //Find insertion point
{
if (cur->item > newNode->item) // while current location has a greater value then what needs to be inserted move pointers forward.
{
prev = cur;
cur = cur->next;
moreToSearch = (cur != NULL);
}
else // if current loacation and what is to be inserted are equal or less then we have found the point of insertion
{
moreToSearch = false;
}
}
if (prev = NULL)
{
newNode->next = head->next;
head = newNode;
}
else
{
prev->next = newNode;
newNode->next = cur;
}
//Insert as only item in list
//Insert in found location
}
int SortedLinkedList::popFirst()
{
sslNode* first;
first = head->next;
head = head->next;
int item = first->item;
return item;
}
Your problem is you forgot an =
if (prev = NULL)
{
newNode->next = head->next;
head = newNode;
}
else
{
prev->next = newNode;
newNode->next = cur;
}
if(prev = NULL)
should be
if(prev == NULL)
right now this is always false because prev becomes null which evaluates to false
and then it fails at
prev->next = newNode;
because your are dereferencing the null pointer.
You'll also want to treat the case where head == NULL before trying to insert anything. Basically if head == NULL, head = newNode;
It crashes because head is initialized to NULL. You probably want to make a dummy head node, depending on your design, or check if its NULL before using it in addItem().
This is how things go down:
SortedLinkedLis
t::SortedLinkedList() // ctor is called
...
head = NULL
SortedLinkedList::addItem(int)
sslNode* cur;
...
cur = head;
...
bool moreToSearch (cur != NULL) // this is surely false
...
if (prev = NULL)
{
newNode->next = head->next;
...//BUT head == NULL ! crash!