Linked List traversal skips values - c++

I'm new to pointers and I'm a bit confused.
I have written a function which merges and sorts two sorted linked lists. However, when I print the list after calling the function it does not have all the values of the new merged list. While debugging the code and examining the variables and memory locations, it looks like it skips over the locations and just jumps to the last memory location. After the function executes I need to have the values in a new list and leaving list1 and list2 empty. This is my method in the header file:
template <class Type>
void orderedLinkedList<Type>::mergeLists(orderedLinkedList<Type> &list1, orderedLinkedList<Type> &list2)
{
nodeType<Type> *lastSmall; //pointer to the last node of the merged list.
nodeType<Type> *first1 = list1.first;
nodeType<Type> *first2 = list2.first;
if (list1.first == NULL){ //first sublist is empty
this->first = list2.first;
list2.first = NULL;
}
else if (list2.first == NULL){ // second sublist is empty
this->first = list1.first;
list1.first = NULL;
}
else{
if (first1->info < first2->info){ //Compare first nodes
this->first = first1;
first1 = first1->link;
lastSmall = this->first;
}
else{
this->first = first2;
first2 = first2->link;
lastSmall = this->first;
}
while (first1 != NULL && first2 != NULL)
{
if(first1->info < first2->info){
lastSmall->link = first1;
lastSmall = lastSmall->link;
first1 = first1->link;
}
else{
lastSmall->link = first2;
lastSmall = lastSmall->link;
first2 = first2->link;
}
} //end while
if (first1 == NULL) //first sublist exhausted first
lastSmall->link = first2;
else //second sublist exhausted first
lastSmall->link = first1;
list1.first = NULL;
list1.last = NULL;
list2.first = NULL;
list2.last = NULL;
}
}
Then in my main.cpp I have:
int main()
{
orderedLinkedList<int> list1;
orderedLinkedList<int> list2;
orderedLinkedList<int> newList;
list1.insert(2);
list1.insert(6);
list1.insert(7);
list2.insert(3);
list2.insert(5);
list2.insert(8);
newList.mergeLists(list1, list2);
newList.print();
return 0;
}
My print function just in case:
template <class Type>
void linkedListType<Type>::print() const
{
nodeType<Type> *current; //pointer to traverse the list
current = first; //set current so that it points to
//the first node
while (current != NULL) //while more data to print
{
cout << current->info << " ";
current = current->link;
}
}//end print
Could someone please tell me what I am doing wrong here? The output should be 2 3 5 6 7 8 but instead it's 2 3 7 8.
Thanks
EDIT:
Here is my insertion function. Note that this function is from the book I'm working with. It is included in the same class that I need to add the mergeLists method to. It is written specifically for ordered lists:
template<class Type>
void orderedLinkedList<Type>::insert(const Type& newItem)
{
nodeType<Type> *current;
nodeType<Type> *trailCurrent;
nodeType<Type> *newNode;
bool found;
newNode = new nodeType<Type>;
newNode->info = newItem;
newNode->link = NULL;
//case1 list is empty
if(this->first == NULL)
{
this->first = newNode;
this->last = newNode;
this->count++;
}
else //if the list is not empty
{
current = this->first;
found = false;
while(current != NULL && !found)
{
if(current->info >= newItem)
found = true;
else
{
trailCurrent = current;
current = current->link;
}
//case2 insert newNode at the head
if(current == this->first)
{
newNode->link = this->first;
this->first = newNode;
this->count++;
}
else //case 3
{
trailCurrent->link = newNode;
newNode->link = current;
if(current == NULL)
this->last = newNode;
this->count++;
}
}
}
}
The 3 cases as according to the book are:
Case 1:
The list is initially empty. The node containing the new item is the only node
and, thus, the first node in the list.
Case 2:
The new item is smaller than the smallest item in the list. The new item goes at
the beginning of the list. In this case, we need to adjust the list’s head pointer—
that is, first. Also, count is incremented by 1.
Case 3:
The item is to be inserted somewhere in the list.
Case 3a:
The new item is larger than all the items in the list. In this case, the new
item is inserted at the end of the list. Thus, the value of current is NULL
and the new item is inserted after trailCurrent. Also, count is incremented
by 1.
Case 3b:
The new item is to be inserted somewhere in the middle of the list. In this
case, the new item is inserted between trailCurrent and current.
Also, count is incremented by 1.

The bug is in your insertion method. When you call print on the lists after inserting, you will note that the last value gets overriden:
list1.insert(2); list1.print();
list1.insert(6); list1.print();
list1.insert(7); list1.print();
list2.insert(3); list2.print();
list2.insert(5); list2.print();
list2.insert(8); list2.print();
will output:
2
2 6
2 7
3
3 5
3 8
This is because every iteration trailCurrent->link = newNode; gets called, cutting of the list the first time this happens.
So for example when 7 is inserted in list1, the loop will first set trailCurrent->link to 7 when trailCurrent is 2, and then continue and set trailCurrent->link to 7 when trailCurrent is 6. But since 2 now points to 7 and not to 6, the chain is lost, and you're stuck with only 2 and 7.
Get another book
The book you are using to learn this is outdated. C style pointers and manual memory allocation should not be used in modern C++. Try to get a modern book that teaches how to use smart pointers and modern collections, and that teaches proper debugging techniques, so you can easily detect problems as the one you stumbled over now.

Thanks to everyone who has tried to help. In the end it was a simple logic error.
I inadvertently added a curly bracket to the end of my while loop in my insertion method which resulted in the loop executing code that it wasn't supposed to more than once causing strange behavior. See the corrected code below:
while(current != NULL && !found)
{ //<-- Removed this
//code
this->count++;
}
} //<-- Removed this
And now the working code is:
template<class Type>
void orderedLinkedList<Type>::insert(const Type& newItem)
{
nodeType<Type> *current;
nodeType<Type> *trailCurrent;
nodeType<Type> *newNode;
bool found;
newNode = new nodeType<Type>;
newNode->info = newItem;
newNode->link = NULL;
//case1 list is empty
if(this->first == NULL)
{
this->first = newNode;
this->last = newNode;
this->count++;
}
else //if the list is not empty
{
current = this->first;
found = false;
while(current != NULL && !found)
if(current->info >= newItem)
found = true;
else
{
trailCurrent = current;
current = current->link;
}
//case2 insert newNode at the head
if(current == this->first)
{
newNode->link = this->first;
this->first = newNode;
this->count++;
}
else //case 3 insert newNode anywher in the list
{
trailCurrent->link = newNode;
newNode->link = current;
if(current == NULL)
this->last = newNode;
this->count++;
}
}
}

Related

Dummy head node circular linked list, deletion problems

I am currently learning about circular linked lists and I am having problems with a circular linked list template. It is derived from an ADT linked list type.
The problems I am having are with deletion of nodes, in some occasions the program will just crash when I delete them. I know I need to implement a dummy node of some sort when I create a list to prevent this happening however I do not know were in the code to do this.
I have looked at other posts regarding this however I am still lost.
If anyone could share some guidance into how to implement this I would be so
grateful.
Thank you
Insert:
template <class Type>
void unorderedCircularLinkedList<Type>::insertFirst(const Type& newItem)
{
nodeType<Type> *newNode;
nodeType<Type> header; <--- implement here?
header.link = &header; <---- dereference the header?
newNode = new nodeType<Type>; //create the new node
newNode->info = newItem; //store the new item in the node
if (first == NULL)
{
first = newNode;
last = first;
last->link = first;
}
else
{
last->link = newNode; //make last point to new node
newNode->link = first; //make new node point to first
first = newNode; //make first point to new node
}
count++; //increment count
}
Delete:
template <class Type>
void unorderedCircularLinkedList<Type>::deleteNode(const Type& deleteItem)
{
nodeType<Type> *current; //pointer to traverse the list
nodeType<Type> *trailCurrent; //pointer just before current
bool found;
if (first == NULL) //Case 1; the list is empty.
cout << "Cannot delete from an empty list."
<< endl;
else
{
if (first->info == deleteItem) //Case 2
{
current = first;
count--;
if (first->link == first) //the list has only one node
{
first = NULL;
last = NULL;
}
else if (first->link == last) //the list has two nodes
{
first = first->link;
first->link = first;
last = first;
}
else
{
first = first->link;
last->link = first;
}
delete current;
}
else //search the list for the node with the given info
{
found = false;
trailCurrent = first; //set trailCurrent to point to the first node
current = first->link; //set current to point to the second node
/* set pointer to point to the last node*/
while (current != NULL && !found)
if (current->info != deleteItem)
{
trailCurrent = current;
current = current->link;
}
else
found = true;
if (found) //Case 3; if found, delete the node
{
trailCurrent->link = current->link;
if (current == last)
first = first->link;
delete current;
count--;
//delete the node from the list
}
else
cout << "The item to be deleted is not in the list." << endl;
}
}
}
your curly braces are messed up
if (first->info == deleteItem) //Case 2
{
current = first;
count--;
//missing '}' here
if (first->link == first) //the list has only one node
{
first = NULL;
last = NULL;
}
and i think there's an extra one at the end you will find out when you add the above one

Order Link List

I have a base class called linkList and two derived class. One order link list class and unorder link list class. My order link list class is not working and i have no idea why.When i insert 3 numbers into the list it work but when i insert more than 4 values it messes up. It will also say the length of the list is larger than what it actually is. [enter image description here][1]
void insert(const T& newItem){
nodeType<T> *current;
nodeType<T> *trailCurrent=nullptr;
nodeType<T> *newNode;
bool found;
newNode = new nodeType<T>;
newNode->info = newItem;
newNode->next = nullptr;
//if the list is empty add to empty list
if (this->first == nullptr){
this->first = newNode;
this->last = newNode;
this->count++;
}
else {
current = this->first;
found = false;
while (current != nullptr && !found){
if (current->info >= newItem)
found = true;
else{
trailCurrent = current;
current = current->next;
}
//if current value is first item into the list insert into the front
if (current == this->first){
newNode->next = this->first;
this->first=newNode;
this->count++;
}
else{
trailCurrent->next = newNode;
newNode->next=current;
if (current == nullptr)
this->last = newNode;
this->count++;
}
}
}
}

Having trouble figure out why my doubly linked list is falling apart and I could use some direction [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Full disclosure: This is a project for my class, but I'm not here to ask you to do my homework for me. I'm looking for a little direction as to what I seem to be missing.
The assignment: From a file of formatted data (see below). You are to create 3 doubly linked lists. (so one set of data with three "chains" that orders the data numerically) If you come across an piece of data with the same timestamp as a previous piece of data, that data is considered to be unreliable and needs to be deleted from the doubly linked list.
The Problem: I have four linked list heads, timeHead, tempHead, and windHead are for the data being read in from the file. The last is duplHead (duplicateHead) is for a list of duplicates. My issue is that whenever I try to delete a particular node from my linked list. I cant seem to do it correctly. I either crash the program or the doubly linked list falls apart.
Here is my code: I feel my main problem is either not creating the list correctly OR not deleting the problem nodes correctly.
The int main function only calls two functions addData and print report. I have included what I felt was relevant.
//ADD TO LINKED LIST
void linkedlist::addToLinkedList(weatherdata *newNode){
int doubleMarker = 0;
weatherdata *newNodeCopy;
weatherdata *currentNode;
weatherdata *nextNode;
newNodeCopy = new weatherdata; // <-- NEW
newNodeCopy = newNode;
/*_____ lINKED lIST FOR TIMESTAMP _____*/
//checks the duplicate list so as not to add a deleted triple
if (isItInDuplicateList(newNode) == 1){
doubleMarker = 1;
}
//if something exists in the list do this: traverse the list, check for duplicates.
if ((timeHead != nullptr) && (doubleMarker != 1)){
currentNode = timeHead;
while (currentNode != nullptr){
//if its the same as another item DELETE
if (newNode->time == currentNode->time) {
addToDuplicateList(newNode);
deleteNodeFromList(newNode);
doubleMarker = 1; // <-- this double marker will ensure that the function doesnt add a duplicate item
break;
}
currentNode = currentNode->timeN;
}
}
//if the incoming number is not a duplicate of something we already have on our list we add it
if (doubleMarker != 1){
//very first item on list
if (timeHead == nullptr){
timeHead = newNodeCopy;
}
//first position on list
else if (newNode->time < timeHead->time){
nextNode = timeHead;
timeHead = newNodeCopy;
newNodeCopy->timeN = nextNode;
nextNode->timeP = newNodeCopy;
}
//either between 2 entries or at the end of the list
else {
//traverse the list and find the appropriate placement for the newNode
currentNode = timeHead;
nextNode = timeHead->timeN;
//while "not yet at the end of the list"
while (nextNode != nullptr){
//newNode belongs somewhere in between two other entries
if ((currentNode->time < newNode->time) && (newNode->time < nextNode->time)){
currentNode->timeN = newNodeCopy;
newNodeCopy->timeP = currentNode;
newNodeCopy->timeN = nextNode;
nextNode->timeP = newNodeCopy;
break;
}
//otherwise increment currentNode and nextNode and compare again
else {
currentNode = nextNode;
nextNode = nextNode->timeN;
}
}
//newNode goes at the end of the linked List
if (nextNode == nullptr){
currentNode->timeN = newNodeCopy;
newNodeCopy->timeP = currentNode;
}
}
}
/*_____ lINKED lIST FOR TEMPERATURE _____*/
//if the incoming number is not a duplicate of something we already have on our list we add it
if (doubleMarker != 1){
//very first item on list
if (tempHead == nullptr){
tempHead = newNodeCopy;
}
//first position on list
else if (newNode->temp < tempHead->temp){
nextNode = tempHead;
tempHead = newNodeCopy;
newNodeCopy->tempN = nextNode;
nextNode->tempP = newNodeCopy;
}
//either between 2 entries or at the end of the list
else {
//traverse the list and find the appropriate placement for the newNode
currentNode = tempHead;
nextNode = tempHead->tempN;
//while "not yet at the end of the list"
while (nextNode != nullptr){
//newNode belongs somewhere in between two other entries
if ((currentNode->temp <= newNode->temp) && (newNode->temp <= nextNode->temp)){
currentNode->tempN = newNodeCopy;
newNodeCopy->tempN = nextNode;
nextNode->tempP = newNodeCopy;
break;
}
//otherwise increment currentNode and nextNode and compare again
else {
currentNode = nextNode;
nextNode = nextNode->tempN;
}
}
//newNode goes at the end of the linked List
if (nextNode == nullptr){
currentNode->tempN = newNodeCopy;
newNodeCopy->tempP = currentNode;
}
}
}
/*_____ lINKED lIST FOR WINDSPEED _____*/
//if the incoming number is not a duplicate of something we already have on our list we add it
if (doubleMarker != 1){
//very first item on list
if (windHead == nullptr){
windHead = newNodeCopy;
}
//first position on list
else if (newNode->wind < windHead->wind){
nextNode = windHead;
windHead = newNodeCopy;
newNodeCopy->windN = nextNode;
nextNode->windP = newNodeCopy;
}
//either between 2 entries or at the end of the list
else {
//traverse the list and find the appropriate placement for the newNode
currentNode = windHead;
nextNode = windHead->windN;
//while "not yet at the end of the list"
while (nextNode != nullptr){
//newNode belongs somewhere in between two other entries
if ((currentNode->wind <= newNode->wind) && (newNode->wind <= nextNode->wind)){
currentNode->windN = newNodeCopy;
newNodeCopy->windN = nextNode;
nextNode->windP = newNodeCopy;
break;
}
//otherwise increment currentNode and nextNode and compare again
else {
currentNode = nextNode;
nextNode = nextNode->windN;
}
}
//newNode goes at the end of the linked List
if (nextNode == nullptr){
currentNode->windN = newNodeCopy;
newNodeCopy->windP = currentNode;
}
}
}
}
//ADD TO DUPLICATE LIST
void linkedlist::addToDuplicateList(weatherdata *duplicateNode){
weatherdata *currentNode;
weatherdata *nextNode;
weatherdata *addDuplicateNode;
addDuplicateNode = new weatherdata; // <-- NEW
//make a complete copy for the duplicate list (since were going to delete that node)
addDuplicateNode->time = duplicateNode->time;
addDuplicateNode->temp = duplicateNode->temp;
addDuplicateNode->wind = duplicateNode->wind;
addDuplicateNode->timeN = duplicateNode->timeN;
addDuplicateNode->timeP = duplicateNode->timeP;
addDuplicateNode->tempN = duplicateNode->tempN;
addDuplicateNode->tempP = duplicateNode->tempP;
addDuplicateNode->windN = duplicateNode->windN;
addDuplicateNode->windP = duplicateNode->windP;
addDuplicateNode->duplN = duplicateNode->duplN;
if (duplHead == nullptr){
duplHead = addDuplicateNode;
}
else {
currentNode = duplHead;
nextNode = duplHead->duplN;
while (nextNode != nullptr){
currentNode = nextNode;
nextNode = nextNode->duplN;
}
currentNode->duplN = addDuplicateNode;
}
}
/DELETE FROM LINKEDLIST
void linkedlist::deleteNodeFromList(weatherdata *toBeDeletedNode){
weatherdata *currentNode;
weatherdata *nextNode;
currentNode = timeHead;
nextNode = timeHead->timeN;
while (nextNode != nullptr){
if (nextNode->time == toBeDeletedNode->time){
currentNode->timeN = nextNode->timeN;
//currentNode->tempN = nextNode->tempN;
//cout << ".";
delete toBeDeletedNode;
toBeDeletedNode = nullptr;
break;
}
currentNode = nextNode;
nextNode = nextNode->timeN;
}
}
//DUPLICATE LIST CHECK
bool linkedlist::isItInDuplicateList(weatherdata *checkThisNode){
bool found = false;
weatherdata *currentNode;
currentNode = duplHead;
if (duplHead == nullptr){
found = false;
}
else {
do {
if (currentNode->time == checkThisNode->time) {
found = true;
break;
}
currentNode = currentNode->duplN;
} while (currentNode != nullptr);
}
return found;
}
So either the first (long) function linkedlist addToLinkedList();
or the last (short) function linkedlist deleteNodeFromList();
If you need me to post anymore code please let me know and I'll so so.
Again, I feel like I'm either not making the doubly linked list correctly or not deleting it right.
Thanks again!
First take a look at these lines:
newNodeCopy = new weatherdata; // <-- NEW
newNodeCopy = newNode;
In the first line you create a new object of type weatherdata and saves a pointer to the new object in newNodeCopy.
In the second line you overwrite the value of newNodeCopy with the value of newNode which means you have lost the pointer to the new object (i.e. you have a memory leak).
If you want to copy the values from the object that newNode points to into the newly created object, you need to do:
*newNodeCopy = *newNode;
In general I'll recommend that you split the function into three smaller functions (i.e. one for each list). Smaller functions are easier to understand and debug.
Also I noticed this part:
if (isItInDuplicateList(newNode) == 1){
doubleMarker = 1;
}
In all the remaining code in the function you do:
if (doubleMarker != 1){
.....
}
In other words - once doubleMarker is set to 1, you don't execute more code. Therefore you can simplify your code by returning right away. Like:
if (isItInDuplicateList(newNode) == 1){
return;
}
Then you can remove all the if (doubleMarker != 1){ and your code gets more simple to read, understand and debug.
The delete function
Your void linkedlist::deleteNodeFromList(weatherdata *toBeDeletedNode) have some serious problems - consider this:
1) What will happen if timeHead is nullptr ?
2) Where do you check if timeHead->time == toBeDeletedNode->time ?
3) Where do you update the timeP pointer ?
The answers are:
1) Program crash
2) Never - so you can't delete the head element.
3) Never - so your list is broken! You need to add code that updates the "previous" pointer

Search Function in Linked List - C++ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
My aim is to produce a function that searches for a number already in the list and print that it has been found.
My initial idea was to follow my remove function which searches through the list until it finds a number (to then delete).
This seemed the logical way to code the search function. If this isn't correct how would I modify it to search through my list and display that a number has been found?
I have nodes *head, *current and *temp as well as node pointer next and number as the data type in a class on a .h file.
Thank you.
NOTE - I used my remove() function under the search() function.
#include <iostream>
#include <string>
#include <fstream>
#include "LinkedList.h"
using namespace SDI;
int main()
{
LinkedList menu;
menu.insert(5);
menu.insert(4);
menu.insert(2);
menu.insert(3);
menu.insert(8);
menu.remove(4);
menu.reverse();
menu.display();
menu.search(2);
system("pause");
};
LinkedList::LinkedList()
{
head = NULL;
current = NULL;
temp = NULL;
};
LinkedList::~LinkedList()
{
};
void LinkedList::insert(int add) //insert function, data is stored in add from function body
{
Node* newnode = new Node; //definition of add node, make new node and make node* point to it
newnode->next = NULL; //point and set up to last node in the list (nothing)
newnode->number = add; //adds data to list
if (head != NULL) //if head is pointing to object then we have list
{
current = head; //make current pointer point to head
while (current->next != NULL) //check to see if end at list, is it the last node?
{
current = current->next; //advances current pointer to end of list
}
current->next = newnode; //adds new node next to value already stored
}
else
{
head = newnode; //if we don't have element in list
}
};
void LinkedList::remove(int remove) //remove function, data is stored in remove from function body
{
Node* remove1 = NULL; //searches through for same value in remove and deletes
temp = head;
current = head;
while (current != NULL && current->number != remove) //check if current node is one we want to delete...if not advance current pointer to next one
{
temp = current; //keep temp pointer one step behind
current = current->next; //advance to next node, traverse list till at the end
}
if (current == NULL) //pass through whole list and value not found
{
std::cout << "N/A\n";
delete remove1; //removes spare number floating around in memory
}
else
{
remove1 = current; //pointing to value we want to delete
current = current->next; //advances current pointer to next node
temp->next = current; //stops hole that occurs in list, patches this up
if (remove1 == head) //if pointer is pointing to front of list
{
head = head->next; //advance the head to next
temp = NULL;
}
delete remove1;
}
};
void LinkedList::search(int searchNum)
{
Node* searchnumber = nullptr;
temp = head;
current = head;
while (current != NULL && current->number != searchNum)
{
temp = current;
current = current->next;
}
if (current != NULL)
{
searchnumber = current;
current = current->next;
std::cout << "-" << searchnumber << " Found";
}
else
{
std::cout << "N/A";
}
};
void LinkedList::display()
{
current = head; //point to start of list
while (current != NULL) //while it points to something in list
{
std::cout << current->number; //display list starting from start
current = current->next; //advance to next pointer
}
};
void LinkedList::reverse()
{
Node *new_head = nullptr; //create new head as we want it to start from last element
for (current = head; current;) //same as display, ask it to go through list from head then outside loop assign to new head and switch sides
{
temp = current; //keep temp pointer one step behind
current = current->next; //goes through each element in the list
temp->next = new_head; //scrolls through backwards from new head
new_head = temp;
}
head = new_head; //assign head to new head
};
Your search algorithm seems to be wrong. Change it to :
if (current != NULL) // (current == NULL) is wrong because it means the value wasn't found
{
searchnumber = current;
current = current->next;
std::cout << "-" << searchnumber->number << " Found"; // here searchnumber is the node's address. You need to print its value, so use searchnumber->number
}
And you don't need to remove nodes till you find the desired value.
You can just use your search algorithm to find if a number already in the list. If that's what you want.
While a list is unordered a comparison of search algorithms doesn't have any sense. Simply iterate over all nodes one by one and apply match criteria.

Insert a duplicate key value into binary tree

I'm trying to write an insert method for my binary search tree class. I want it to be able to insert a new value into a tree that already has an existing node with this same data value must cause a new node to be created in the right subtree of the existing node. Here's my code. I'm getting an unhandled exception error while trying to compile. I don't know what I did wrong there. If someone can explain the reason why the compiler is giving me error, it would be great. Thanks :)
template <class elemType>
void bSearchTreeType<elemType>::insert
(const elemType& insertItem)
{
nodeType<elemType> *current; //pointer to traverse the tree
nodeType<elemType> *trailCurrent; //pointer behind current
nodeType<elemType> *newNode; //pointer to create the node
newNode = new nodeType<elemType>;
newNode->info = insertItem;
newNode->lLink = NULL;
newNode->rLink = NULL;
if (root == NULL)
root = newNode;
else
{
current = root;
while (current != NULL)
{
trailCurrent = current;
if (current->info == insertItem)
{
current = current->rLink;
trailCurrent->rLink = newNode;
if (newNode->info <= current->info) //this is where the compiler say the error is
newNode->rLink = current;
else
newNode->lLink = current;
}
else if (current->info > insertItem)
current = current->lLink;
else
current = current->rLink;
}//end while
if (trailCurrent->info < insertItem)
trailCurrent->rLink = newNode;
else if (trailCurrent->info > insertItem)
trailCurrent->lLink = newNode;
}
}//end insert
You should make a deal with yourself. This deal can be like this:
The left subtree will have values less or equal than the one in the root and so on.
In code you have:
if (trailCurrent->info < insertItem)
trailCurrent->rLink = newNode;
which after the deal would be like this:
if (trailCurrent->info <= insertItem)
trailCurrent->rLink = newNode;
I'm fairly certain this is what you're trying to do:
template <class elemType>
void bSearchTreeType<elemType>::insert(const elemType& insertItem)
{
nodeType<elemType> **pp = &root;
while (*pp)
{
if (insertItem < (*pp)->info)
pp = &(*pp)->lLink;
else if ((*pp)->info < insertItem)
pp = &(*pp)->rLink);
else break;
}
// note: this is cleaner if the the nodeType constructor
// is parameterized. (hint hint)
nodeType<elemType> *p = new nodType<elemType>;
p->info = insertItem;
p->lLink = NULL;
if (*pp)
{
p->rLink = (*pp)->rLink;
(*pp)->rLink = p;
}
else
*pp = p;
}
How it works
The basics of finding an insertion point for a new non-existing key are mundane, so I'll not cover them. The case of locating an existing key is, however, interesting. We use a pointer-to-pointer to hold the address of each node pointer we encounter while walking down the tree. When we have a match the loop will exit and *pp will not be null. When that happens, our new node has it's right-pointer set to the matched right-pointer, and the matched node's right-pointer becomes the new node. The remainder of the tree remains as-is.
I.e. adding a second 7 in this:
5
3 7
2 4 6 8
results in
5
3 7
2 4 6 7
8
then adding another 3 results in:
5
3 7
2 3 6 7
4 8
All of this, of course, assuming i understood the problem.No attempt at rotations or balancing is done. That I leave to you.
Not sure if this is correct but
trialCurrent = current;
trialCurrent is equal to current
if(current->info == insertItem)
current = current->rLink;
trialCurrent->rlink = newnode;
current is equal to current->rLink, then wouldn't trialCurrent->rLink be equal to current?