I am writing an add method for a Linked List class in C++. The add method is written to handle a variety of situations that may occur based on the input of the method. I have added "cout" statements in order to try and track which loops/if-statements the method is going into, but nothing is being printed from the method. The input for the method are the index of the node and the data that is held in the node.
void linkedList::add(int pos, string item)
{
Node *temp = new Node;
Node *nextTemp = new Node;
if(pos == 0)
{
cout<< "hey";
if(head != NULL)
{
cout<< "hey1";
temp->setData((head->getPosition()+1),
head->getItem(), head->getNextNode());
head->setData(pos, item, temp);
currentNode = head;
size++;
}
else
{
cout<< "hey2";
head->setData(pos, item, temp);
currentNode = head;
size++;
}
}
else if(pos == size)
{
cout<< "hey3";
while(currentNode != NULL)
{
cout<< "hey4";
currentNode = currentNode->nextNode;
}
temp->setData(pos, item, nextTemp);
currentNode->nextNode = temp;
size++;
}
else
{
cout<< "hey5";
for(int i = 0; i<size; i++)
{
cout<< "hey6";
if(i == currentNode->getPosition())
{
cout<< "hey7";
temp->setData(currentNode->getPosition(),
currentNode->getItem(), currentNode->getNextNode());
currentNode->setData(pos, item, temp);
size++;
}
currentNode = currentNode->nextNode;
while(currentNode->getPosition() < (size+1))
{
cout<< "hey8";
currentNode->setPosition(i+1);
currentNode = currentNode->nextNode;
}
}
}
}
Any help would be appreciated. Thank you.
Related
I've been trying to delete a node if the data matches a specific value.
Here's my delete value method:
void del_value(int data)
{
Node *temp = head;
int i = 0;
while(temp!=NULL)
{
if(temp->data == data)
{
del_index(i);
i--; // Since the nodes count will be reduced after deleting, reducing the index by one.
}
i++;
temp = temp->next;
}
}
And here is my del_index method(Which is working correctly):
int getCount()
{
int i = -1;
Node *temp = head;
while(temp!=NULL)
{
temp = temp->next;
i++;
}
return i;
}
void del_index(int pos)
{
int count = getCount();
if(pos == 0)
{
del_start();
}
else if(pos == count)
{
del_last();
}
else if(pos<0 || pos>count)
{
cout<<"Out of range"<<endl;
return;
}
else
{
int i = 1;
Node *temp = head;
while(i<pos)
{
temp = temp->next;
i++;
}
Node *toDel = temp->next;
Node *forward = toDel->next;
temp->next = forward;
delete toDel;
}
}
And here is my main method:
int main()
{
Mylist l;
l.add_start(4);
l.add_start(4);
l.add_start(4);
l.del_value(4);
l.show();
}
But it stucks when it reaches del_value method inside loop. Any idea where am I missing?
Update: (Added del_first and del_last methods
void del_start()
{
if(head == NULL)
{
cout<<"List is empty"<<endl;
return;
}
else
{
Node *temp = head;
head = head->next;
delete temp;
}
}
void del_last()
{
if(head == NULL)
{
cout<<"List is empty"<<endl;
return;
}
else
{
Node *temp = head;
while(temp->next != NULL)
{
tail = temp;
temp = temp->next;
}
tail->next = NULL;
delete temp;
}
}
Your del_value method will not work because you delete the object being pointed to by 'temp' then you dereference it after (with "temp = temp->next").
For your example code, I would cache the 'next' value before your conditional, for example:
Node *next = temp->next;
if(temp->data == data)
{
del_index(i);
i--;
}
i++;
temp = next;
I am assuming you're doing this for practice purposes but I would add the following suggestions:
I wouldn't call del_index here but remove the node inline, within the del_value method. As you have the necessary pointers to be able to remove it. del_index has to traverse your list a second time.
I would also recommend using the containers within the stl instead of rolling your own to avoid encountering issues like this.
struct node
{
string info;
struct node *next;
}*start, *last;
long nodecount=0;
class teditor
{
public:
node* create_node(string);
void insert_pos();
void save();
void display();
void delete_pos();
teditor()
{
start = NULL;
}
};
node *teditor::create_node(string value)
{
struct node *temp, *s;
temp = new(struct node);
if (temp == NULL)
{
cout<<"Memory not allocated "<<endl;
return 0;
}
else
{
temp->info = value;
temp->next = NULL;
return temp;
}
}
void teditor::save()
{
struct node *info;
ofstream listfile;
listfile.open("example.txt",ios::out|ios::app |ios::binary) ;
node *temp;
temp=start;
if(!listfile){
cout<<"\nError";
}
else{
while(temp!=NULL)
{
listfile.write((char*)(temp),sizeof(nodecount));
temp=temp->next;
}
}
listfile.close();
cout<<"\n\n\n\t\tLink list has been saved in file example.txt in current folder.";
cout<<"\n\n\t\tPress a key to continue ... ";getch();
}
void teditor::insert_pos()
{
string value; int counter;
int pos;
cout<<"Enter the value to be inserted: ";
cin>>value;
struct node *temp, *s, *ptr;
temp = create_node(value);
cout<<"Enter the postion at which node to be inserted: ";
cin>>pos;
nodecount++;
int i;
s = start;
while (s != NULL)
{
s = s->next; counter++;
}
if (pos == 1)
{
if (start == NULL)
{
start = temp;
start->next = NULL;
}
else
{
ptr = start;
start = temp;
start->next = ptr;
}
}
else if (pos > 1 )
{
s = start;
for (i = 1; i < pos; i++)
{
ptr = s;
s = s->next;
}
ptr->next = temp;
temp->next = s;
}
else
{
cout<<"Positon out of range"<<endl;
}
}
void teditor::display()
{
/*
Need to merge as a string and show to display just in one line like writing
why cannot save health because of application saving pointers.
*/
node *temp;
temp=start;
cout<<"\n\n\n";
while(temp)
{
cout<<"\t\t\t"<<temp->info;
temp=temp->next;
}
cout<<"\n\n\t\t "<<nodecount<<" records displayed ,Press a key to continue.....";getch();
}
void teditor::delete_pos()
{
int pos, i, counter = 0;
if (start == NULL)
{
cout<<"List is empty"<<endl;
return;
}
cout<<"Enter the position of value to be deleted: ";
cin>>pos;
struct node *s, *ptr;
s = start;
if (pos == 1)
{
start = s->next;
}
else
{
while (s != NULL)
{
s = s->next;
}
if (pos > 0 && pos <= counter)
{
s = start;
for (i = 1;i < pos;i++)
{
ptr = s;
s = s->next;
}
ptr->next = s->next;
}
else
{
cout<<"Position out of range"<<endl;
}
free(s);
}cout<<s<<" Element Deleted"<<endl;nodecount--;
cout<<"There is left "<<nodecount<<" nodes"<<endl;
}
Hi,guys!I have problem while I trying to save my linked list to txt.Everytime I tryin and txt gave me a chinese writing.Teacher also said I need to merged with string or I need to give node to string that application can easily save that string line.Maybe because of I 'm trying to write node *temp.Anybody know how can I solve my problem?After other processes it will be copy,cut,paste and replace with nodes.
Change
listfile.write((char*)(temp),sizeof(nodecount));
to
listfile << temp->info;
You did not want to write the pointer temp into your files, you wanted the info that is inside the node that temp is pointing at. Then why you are writing temp instead of writing the info? YOu could do that "through" your pointer temp, right?
The below will do the above for you:
listfile << temp->info;
ok, you have a serialization problem. You want text in the file. But you are simply dumping memory to the file.
listfile.write((char*)(temp),sizeof(nodecount));
just writes the raw memory of a node.
Ask yourself - what should the text file look like? What do you expect it to look like in an editor. THen you have to write code to do that.
YOu need to do
listfile << temp->info
How do you want to save the next and prior. Maybe it is implicit in the ordering. SO this is all you need. Maybe you need line numbers ans to say next=4, prior=14
Your problem will be solved after doing these steps:
Right click on the project name, go to properties
In general -> project defaults -> character set
Choose not set
I'm working a project for class that requires creating a binary search tree of criminal names with up to 8 attributes per criminal.
I set up a string array att[] that will read in the attributes for each criminal, and then be passed to my BSTInsert class function. Through debugging I can see that the array is correct when it's just in the setupTree function. Once it's passed to BSTInsert, instead of having each string it only has one string, and on top of that nothing is copied from the array to the node in the tree.
Can anyone tell me what I'm doing wrong?
Here's my code for setting up the tree:
void setupTree(BST& criminals)
{
ifstream fin("criminals.txt");
string temp;
fin >> temp;
//FINISHED means it has all the criminals
while (temp != "FINISHED")
{
//SUSPECT lets it know to read in a new name and new attributes
if (temp == "SUSPECT")
{
string name;
string att[8];
int count = 0;
fin >> temp;
//if there is a false "suspect" line, quit
if (temp == "FINISHED") return;
name = temp;
fin >> temp;
while (temp != "SUSPECT" && temp != "FINISHED")
{
att[count] = temp;
count++;
fin >> temp;
}
criminals.BSTInsert(name, att, count);
}
}
}
Here's my class function for inserting a node:
bool BST::BSTInsert(treetype name, treetype att[], int count)
{
//gets the memory for the node. If unable, returns fail.
node* newNode = new node;
if (newNode == NULL)
{
return false;
}
newNode->count = 0;
//initializes the node with the given information to place
for (int i = 0; i < count; i++)
{
newNode->att[newNode->count] = att[count];
newNode->count++;
}
newNode->name = name;
newNode->left = newNode->right = NULL;
//if the tree is empty, creates this node as the root
if (root == NULL)
{
root = newNode;
root->parent = NULL;
}
else
{
//the tree is not empty, so it will use the parent to insert the node
node* current = root;
node* parent = NULL;
//finds the insertion spot
while (current != NULL)
{
parent = current;
if (name <= current->name)
{
current = current->left;
}
else
{
current = current->right;
}
}
//inserts the new node onto the correct side of the parent
if (name <= parent->name)
{
parent->left = newNode;
}
else
{
parent->right = newNode;
}
newNode->parent = parent;
}
return true;
treetype att[] doesn't pass an array, it passes a pointer to an array - it decays to treetype att*.
That said, your problem is here:
for (int i = 0; i < count; i++)
{
newNode->att[newNode->count] = att[count];
newNode->count++;
}
This copies the wrong element of att (beyond the end of the array) into every att in newNode. What you meant was
for (int i = 0; i < count; i++)
{
newNode->att[newNode->count] = att[newNode->count];
newNode->count++;
}
// ConsoleApplication1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
Node* head = NULL;
int size;
Node* tail = NULL;
void printLinkedList() {
Node *search = head;
if (head == NULL) {
cout << "linkedlist is empty" << endl;
}
else {
while (search != NULL){
cout << search->data << endl;
search = search->next;
}
}
}
int sizeLinkedList() {
size = 1;
Node* current = head;
while (current->next != NULL) {
current = current->next;
size = size + 1;
}
cout << size << endl;
return size;
}
Node *getNode(int position){
Node *current = head;
for (int i = 0; i<position; i++)
{
current = current->next;
}
return current;
}
void appendNode(int n) {
Node *newNode = new Node; //creating new node
newNode->data = n;
newNode->next = NULL;
if (head == NULL)
{
head = newNode;
return;
}
else {
Node *current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
void insertNode(int n, int position) {
Node *newNode = new Node;
newNode->data = n;
newNode->next = NULL;
int size = sizeLinkedList();
if (position = 0){
if (head == NULL) {
head = newNode;
}
else{
newNode->next = head;
head = newNode;
}
}
else if (position == size) {
appendNode(n);
}
else {
Node *prevNode = getNode(position-1);
Node *nextNode = getNode(position);
prevNode->next = newNode;
newNode->next = nextNode;
}
}
void deleteNode(int position) {
Node *currentNode;
int size = sizeLinkedList();
if (size == 0) {
return;
}
if (position == 0) {
currentNode = head->next;
head = currentNode;
}
else if (position == size-1) {
getNode(position - 1)->next = NULL;
delete getNode(position);
}
else {
getNode(position - 1)->next = getNode(position+1);
delete getNode(position);
}
}
//making a dynamic array only via pointers in VC++
void makeArray() {
int* m = NULL;
int n;
cout << "how many entries are there?"<<endl;
cin >> n;
m = new int[n];
int temp;
for (int x = 0; x < n; x++){
cout << "enter item:"<< x+1<< endl;
cin >> temp;
*(m + x) = temp;
}
for (int x = 0; x < n; x++){
cout << x+1 + ":" << "There is item: "<<*(m+x) << endl;
}
delete[]m;
}
int main() {
int x;
//makeArray();
appendNode(1);
appendNode(2);
appendNode(32);
appendNode(55);
appendNode(66);
//insertNode(2, 0);
printLinkedList();
deleteNode(3);
printLinkedList();
sizeLinkedList();
cin >> x;
}
Im just trying to code a Linked List with a couple of functions for practice
My Delete function, the last else statement isnt working, and logically I cant figure out why,
as for my insert function none of the statements are working, not even at head or position 0. However appending items, returning size, printing the list, deleting the first and last elements works.
thanks!
sizeLinkedList won't work correctly if the list is empty (it cannot return 0)
you are using size as different variables at different scopes (at main scope, and within deleteNode). This is pretty confusing although not strictly wrong.
in deleteNode, this sequence won't work:
else if (position == size-1) {
getNode(position - 1)->next = NULL;
delete getNode(position);
}
setting the next pointer on the node prior to position to NULL will interfere with the attempt to getNode(position) in the very next line, because it traverses the list based on next. The fix is to reverse these two lines.
Likewise, your last sequence in deleteNode won't work for a similar reason, because you are modifying the next pointers:
else {
getNode(position - 1)->next = getNode(position+1);
delete getNode(position); // this list traversal will skip the node to delete!
}
the solution here is like this:
else {
currentNode = getNode(position);
getNode(position - 1)->next = getNode(position+1);
delete currentNode;
}
I've also re-written the insertNode function incorporating the comment provided by #0x499602D2 .
Here's a modified version of your code that has your current sequence in main fixed:
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
Node* head = NULL;
int size = 0;
Node* tail = NULL;
void printLinkedList() {
Node *search = head;
if (head == NULL) {
cout << "linkedlist is empty" << endl;
}
else {
while (search != NULL){
cout << search->data << endl;
search = search->next;
}
}
}
int sizeLinkedList() {
size = 0;
if (head->next != NULL){
size = 1;
Node* current = head;
while (current->next != NULL) {
current = current->next;
size = size + 1;
}
}
cout << size << endl;
return size;
}
Node *getNode(int position){
Node *current = head;
for (int i = 0; i<position; i++)
{
current = current->next;
}
return current;
}
void appendNode(int n) {
Node *newNode = new Node; //creating new node
newNode->data = n;
newNode->next = NULL;
size++;
if (head == NULL)
{
head = newNode;
return;
}
else {
Node *current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
void insertNode(int n, int position) {
Node *newNode = new Node;
newNode->data = n;
newNode->next = NULL;
if (position == 0){
newNode->next = head;
head = newNode;
}
else if (position == sizeLinkedList()) {
appendNode(n);
}
else {
Node *prevNode = getNode(position-1);
Node *nextNode = getNode(position);
prevNode->next = newNode;
newNode->next = nextNode;
}
}
void deleteNode(int position) {
Node *currentNode;
int my_size = sizeLinkedList();
if ((my_size == 0) || (position > my_size)) {
return;
}
if (position == 0) {
currentNode = head->next;
head = currentNode;
}
else if (position == size-1) {
delete getNode(position);
getNode(position - 1)->next = NULL;
}
else {
currentNode = getNode(position);
getNode(position - 1)->next = getNode(position+1);
delete currentNode;
}
}
//making a dynamic array only via pointers in VC++
void makeArray() {
int* m = NULL;
int n;
cout << "how many entries are there?"<<endl;
cin >> n;
m = new int[n];
int temp;
for (int x = 0; x < n; x++){
cout << "enter item:"<< x+1<< endl;
cin >> temp;
*(m + x) = temp;
}
for (int x = 0; x < n; x++){
cout << x+1 + ":" << "There is item: "<<*(m+x) << endl;
}
delete[]m;
}
int main() {
int x;
//makeArray();
appendNode(1);
appendNode(2);
appendNode(32);
appendNode(55);
appendNode(66);
insertNode(2, 0);
printLinkedList();
deleteNode(3);
printLinkedList();
sizeLinkedList();
}
I have implemented an insertion sort in a double link list (highest to lowest) from a file of 10,000 ints, and output to file in reverse order.
To my knowledge I have implemented such a program, however I noticed in the ouput file, a single number is out of place. Every other number is in correct order.
The number out of place is a repeated number, but the other repeats of this number are in correct order. Its just strange how this number is incorrectly placed. Also the unsorted number is only 6 places out of sync.
I have looked through my program for days now with no idea where the problem lies, so I turn to you for help.
Below is the code in question,
(side note: can my question be deleted by myself? rather my colleges dont thieve my code, if not how can it be deleted?)
void DLLIntStorage::insertBefore(int inValue, node *nodeB)
{
node *newNode;
newNode = new node();
newNode->prev = nodeB->prev;
newNode->next = nodeB;
newNode->value = inValue;
if(nodeB->prev==NULL)
{
this->front = newNode;
}
else
{
nodeB->prev->next = newNode;
}
nodeB->prev = newNode;
}
void DLLIntStorage::insertAfter(int inValue, node *nodeB)
{
node *newNode;
newNode = new node();
newNode->next = nodeB->next;
newNode->prev = nodeB;
newNode->value = inValue;
if(nodeB->next == NULL)
{
this->back = newNode;
}
else
{
nodeB->next->prev = newNode;
}
nodeB->next = newNode;
}
void DLLIntStorage::insertFront(int inValue)
{
node *newNode;
if(this->front == NULL)
{
newNode = new node();
this->front = newNode;
this->back = newNode;
newNode->prev = NULL;
newNode->next = NULL;
newNode->value = inValue;
}
else
{
insertBefore(inValue, this->front);
}
}
void DLLIntStorage::insertBack(int inValue)
{
if(this->back == NULL)
{
insertFront(inValue);
}
else
{
insertAfter(inValue, this->back);
}
}
ifstream& operator>> (ifstream &in, DLLIntStorage &obj)
{
int readInt, counter = 0;
while(!in.eof())
{
if(counter==dataLength) //stops at 10,000
{
break;
}
in >> readInt;
if(obj.front != NULL )
{
obj.insertion(readInt);
}
else
{
obj.insertBack(readInt);
}
counter++;
}
return in;
}
void DLLIntStorage::insertion(int inValue)
{
node* temp;
temp = this->front;
if(temp->value >= inValue)
{
insertFront(inValue);
return;
}
else
{
while(temp->next!=NULL && temp!=this->back)
{
if(temp->value >= inValue)
{
insertBefore(inValue, temp);
return;
}
temp = temp->next;
}
}
if(temp == this->back)
{
insertBack(inValue);
}
}
Thankyou for your time.
I don't like this part
else
{
while(temp->next!=NULL && temp!=this->back)
{
if(temp->value >= inValue)
{
insertBefore(inValue, temp);
return;
}
temp = temp->next;
}
}
if(temp == this->back)
{
insertBack(inValue);
}
Imagine what happens if inValue is greater than all values except this->back->value. It gets inserted at the end instead before this->back. By the way, You are inserting equal integers in the reversed order, they are read. For integers it doesn't matter that much, but it could if You inserted other objects. I would change the code of the insertion method to this:
node* temp;
temp = this->front;
while(temp!=NULL)
{
if(temp->value > inValue)
{
insertBefore(inValue, temp);
return;
}
temp = temp->next;
}
insertBack(inValue);
Just some remarks.
while(!in.eof())
This will not stop the inside of the loop from seeing an EOF error. You want
while ( in >> readInt )
Also,
if(this->front == NULL)
and
void DLLIntStorage::insertion(int inValue)
{
node* temp;
temp = this->front;
if(temp->value >= inValue)
do not mix. Either the front can be NULL, or it cannot. Likewise, you need to decide whether to use temp->next!=NULL or temp!=this->back, but not both, as a loop termination condition.
My guess would be that some inconsistency between multiple linking conventions is causing the errant value to get pushed into the middle of the list.