I've been trying to create an ordered double linked list and then print it out forwards and backwards using recursion. I don't know if I'm adding nodes to the linked list incorrectly or if my problem is in my print functions.
Main
int main() {
ifstream addData;
addData.open("proj1adds.data");
LinkedList<int> List;
Node<int> *head = NULL:
int add;
int i = 0;
while (!addData.eof()){
addData >> add;
List.add(i, add);
i++;
}
}
this is my add function
template < typename T >
void LinkedList < T >::add(int index, T element)
{
if (index == 0){
addFirst(element);
}
else if (index >= size){
addLast(element);
}
else
{
Node < T > * current = head;
for (int i = 1; i < index; i++)
current = current->next;
Node < T > * temp = current->next;
current->next = new Node < T > (element);
(current->next)->prev = current;
(current->next)->next = temp;
size++;
}
}
And these are my print functions
template<typename T>
void LinkedList<T>::printForward(Node<T> *head){
if(head==NULL){
return;
}
cout << head->element << endl;
printForward(head->next);
}
template<typename T>
void LinkedList<T>::printBackward(Node<T> *head){
if(head==NULL){
return;
}
printBackward(head->next);
cout << head->element << endl;
}
I think that I've loaded the data into the nodes, but I'm not sure if its ordered because I cant print it.
In a comment (but not in your question) you say that you're calling printFowards(head) and printBackwards(head) in main(). But in main(), the variable head is a local variable that is set to NULL. So the functions abort, and when you comment out the exit condition [shudder] you dereference a null pointer and get Undefined Behavior.
Maybe the list is being constructed correctly; it doesn't matter because your calls to the printing functions have no connection to the list.
Related
I am writing a code to rotate a singly linked list counter-clockwise by K number of nodes. I wrote the following code. For example for the input linked list, 1,2,3,4,5,6,7,8 the rotate function Node *rotate(Node *head, int k){} returns the head pointer to the linked list 5,6,7,8,1,2,3,4. I wrote the following code. In this code, If I call print(head) inside the rotate function then it gives correct output but once it returns the head pointer to main then it either throws SIGSEV or is producing 1,2,3,4.
#include <iostream>
using namespace std;
class List {
public:
int data;
List *next;
explicit List(int element) : data(element), next(nullptr){}
};
List *insert() {
int n, i, value;
List *temp = nullptr, *head = nullptr;
cin >> n;
for(i = 0; i < n; ++i) {
cin >> value;
if(i == 0) {
head = new List(value);
temp = head;
continue;
} else {
temp ->next = new List(value);
temp = temp->next;
}
}
return head;
}
void print(List *start) {
while(start != nullptr) {
cout << start ->data << " ";
start = start->next;
}
}
List* rotate(List* head, int k) {
List *traverse = head, *temp = head;
List *kth, *end;
int i = 0;
while(i < k - 1) {
traverse = traverse ->next;
++i;
}
kth = traverse;
while(traverse->next != nullptr) {
traverse = traverse->next;
}
end = traverse;
head = kth->next;
kth->next = nullptr;
end->next = temp;
print(head);
return head;
}
int main() {
int k;
List *head = insert();
cin >> k;
print(head);
cout << endl;
rotate(head, k);
print(head);
return 0;
}
PS: I am only allowed to change the rotate function.
I'm attempting to write a function to see whether or not there are more nodes to search through in the linked list, and what I have so far gives me a seg fault. Any ideas on what I need to change?
Iterator class:
bool Iterator::hasNext(){
Node* temp = current->getNext();
if(temp == NULL){
return(false);
}
else{
return(true);
}
List Class:
void List::addFirst(void* obj)
{
Node* newNode = new Node(obj);
newNode->setNext(head);
head = newNode;
}
Node Class:
Node* Node::getNext()
{
return(next);
}
Main class:
List list1;
for(int i = 0; i < 4; i++) {
list1.addFirst(stars[i]);
}
Iterator itr(&list1);
while(itr.hasNext()) {
std::cout << ((char*)itr.get()->getItem())
<< std::endl;
itr.advance();
}
I am not sure about it but you can
Try
//directly accessing the next and comparing
return if(current->getNext() == NULL)
directly without storing it in a separate temp node .
I was working on a homework assignment with linked lists, and while it seems that the code itself is spitting out the "right" answer (what the teacher wants it to), it brings up an error message when running that states "the program has stopped working (it will be forced closed, reported to windows, etc)". The program doesn't force close after closing this dialogue, and besides this, seems to be exactly what my teacher is looking for in the assignment. Any suggestions?
#include <iostream> // Provides cout
#include <cstdlib> // Provides EXIT_SUCCESS
using namespace std; // Allows all standard library items to be used
struct node
{
int data;
node* link;
};
void insert_at_head(node*& head, int entry)
//Precondition: head is the head pointer of a linked list, entry is
// a non-negative integer
//Postcondition: Inserts a new node with data field set to entry at the
// beginning of the linked list head
{
node* n;
n = new node;
n->data = entry;
n->link = head;
head = n;
}
void print(const node* head)
//Precondistion: head is the head pointer of a linked list
//Postcondition: Prints that linked list
{
const node* cursor;
cout << "The linked list is:" << endl;
for (cursor=head; cursor != NULL; cursor=cursor->link)
cout << cursor-> data << " ";
cout << endl;
}
void delete_last(node* & head)
{
while (head->link != NULL)
{
int i;
for(i = 0; 10 >= i; i++)
{
struct node* secondlast = head;
struct node* last = head->link;
while(last->link != NULL)
{ struct node* t = last;
secondlast = t;
last = last->link;
}
delete last;
secondlast->link = NULL;
cout << "I have deleted the last element in the linked list" << endl;
print(head);
}
}
while (head == NULL)
{
return;
}
}
int main( )
{ int i;
node* head;
head = NULL;
for(i = 1; 10 >= i; i++)
{
insert_at_head(head, i);
}
print(head);
delete_last(head);
return EXIT_SUCCESS;
}
If you can follow my main below, I run the program, I am able to enter an integer, it finds the next prime number, then asks for data. Once I enter data once, the program hangs. Seems to be in an infinite loop, or something. It doesn't crash. When I pause it, it brings up read.c file with an arrow on line 256. Not sure what this means whatsoever. Any help would be much appreciated.
I have the following class and member function declarations in hashtable.h:
#ifndef HASHTABLE_H
#define HASHTABLE_H
#define TRUE 1
#define FALSE 0
#define VERBOSE 0x01
#define NON_VERBOSE 0x02
#include "linkedlist.h"
class hashTable{
public:
int keys;
int tableSize;
linkedList<int> **table;
hashTable(const int n);
//~hashTable();
void hash(int value);
int search(int value);
int divisionMethod(int value, int sizeOfTable);
int midSquareMethod(int value, int sizeOfTable);
int total();
void printHashTable();
int next_prime(int value, char flag);
};
// constructor
hashTable::hashTable(const int n){
linkedList<int> newList;
tableSize = next_prime(n, VERBOSE);
cout << "Table size is: " << tableSize << "\n"; // for debugging
system("pause"); // for debugging
table = new linkedList<int>*[tableSize];
for (int i = 0; i < tableSize; i++)
table[i] = { new linkedList<int> };
}
// Compute the Hash Function and "Hash" element into table
void hashTable::hash(int value){
table[value % tableSize]->addToHead(value);
keys++;
//divisionMethod(midSquareMethod(value, tableSize), tableSize)
}
// Simple Search Function
// Returns the element searched for if found, 0 otherwise
int hashTable::search(int value){
return(table[value % tableSize]->search(value));
}
// Divsion Method for producing a semi-unique key
int hashTable::divisionMethod(int value, int sizeOfTable){
int key;
key = value % sizeOfTable;
return(key);
}
// Middle Square Method for producing a semi-unique key
int hashTable::midSquareMethod(int value, int sizeOfTable){
int key;
key = ((value * value) & 0x0ff0) >> 4; // pick the middle 8 bits
return(key);
}
// Returns the total number of keys in the table
int hashTable::total(){
return(keys);
}
// Print the hash table (for demonstration purposes
void hashTable::printHashTable(){
int i = 0, valueToPrint;
while (i < tableSize){
cout << i << ": ";
valueToPrint = table[i]->removeFromHead();
while (valueToPrint != 0){
cout << valueToPrint << " -> ";
valueToPrint = table[i]->removeFromHead();
}
cout << "|" << endl;
i++;
}
}
int hashTable::next_prime(int value, char flag){
int FOUND = FALSE;
int n;
while (!FOUND) {
for (n = 2; (n * n) <= value && (value % n) != 0; ++n);
if ((n * n) <= value) {
if (flag == VERBOSE)
cout << value << " is divisible by " << n << "\n";
value++;
}
else {
if (flag == VERBOSE)
cout << "The next largest prime is " << value << "\n";
FOUND = TRUE;
}
}
return(value);
}
#endif
Here is my linkedlist.h:
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
#include <iostream>
using namespace std;
template <class TYPE>
class Node{
public:
TYPE data;
Node* next;
// constructor
Node(TYPE const& x){
data = x;
next = NULL;
}
};
template <class TYPE>
class linkedList{
//struct Node{
// TYPE data;
// Node *next;
//};
public:
Node<TYPE> *head;
Node<TYPE> *tail;
int size;
// constructor
linkedList(){
head = NULL;
tail = NULL;
size = 0;
}
~linkedList();
void addToHead(TYPE value);
void addToTail(TYPE value);
TYPE removeFromHead();
TYPE removeFromTail();
TYPE search(TYPE searchData);
TYPE isEmpty();
};
//destructor
template <class TYPE>
linkedList<TYPE>::~linkedList(void){
while (head){
Node<TYPE> *temp = head;
head = head->next;
delete temp;
}
}
// Insert an element at the head (start) of the linked list
template <class TYPE>
void linkedList<TYPE>::addToHead(TYPE value){
Node<TYPE> *newNode = new Node<TYPE>(value);
if (isEmpty())
head = newNode;
else{
newNode->next = head;
head = newNode;
}
}
// Add an element to the tail (end) of the linked list
template <class TYPE>
void linkedList<TYPE>::addToTail(TYPE value){
Node<TYPE> *newNode = new Node<TYPE>(value);
Node *tempPtr;
if(isEmpty()){
head = newNode;
tail = newNode;
}
else{
tail->next = newNode;
tail = tail->next;
}
}
// Remove an element from start of Linked List
template <class TYPE>
TYPE linkedList<TYPE>::removeFromHead(){
TYPE tempValue;
Node<TYPE> *temp;
if (head){
tempValue = head->data;
temp = head;
if (head == tail)
head = tail = 0;
else
head = head->next;
delete temp;
return tempValue;
}
else
return 0;
}
// Remove an element from the end of the linked list
template <class TYPE>
TYPE linkedList<TYPE>::removeFromTail(){
TYPE tempValue;
Node *temp;
if (tail){
tempValue = tail->data;
if (head == tail){
delete head;
head = tail = 0;
}
else{
for (temp = head; temp->next != tail; temp = temp->next);
delete tail;
tail = temp;
tail->next = 0;
}
return tempValue;
}
else
return 0;
}
// Search for an element in the linked list
// Will return the element if found, otherwise it returns 0
template <class TYPE>
TYPE linkedList<TYPE>::search(TYPE searchData){
Node<TYPE> *temp;
temp = head;
while (temp->next != tail){
if (tail->data == searchData)
return searchData;
if (temp->data == searchData)
return searchData;
else
temp = temp->next;
}
return 0;
}
// isEmpty() function checks if head == NULL
template <class TYPE>
TYPE linkedList<TYPE>::isEmpty(){
return(head == NULL);
}
#endif
Here is my main:
#include "hashtable.h"
int main(){
int n, input;
cout << "Enter an integer: ";
cin >> n;
cout << "\n\n";
hashTable myHashTable(n);
cout << "Enter some values into the table:" << endl;
cin >> input;
while (input != 0){
myHashTable.hash(input);
cin >> input;
}
myHashTable.printHashTable();
}
Something must be wrong, you have in attribute of your hashTable class ... a hashTable pointer. It must be a linkedlist pointer, nop ?
I did find out what was causing all this. It was the way that I was implementing the linked lists in my array of pointers. Pretty much just programmer error from long nights. Of course there is a lot wrong with my code that I posted here, which I fixed it all, e.g. search function in my hash class, etc.,
Here is what I changed that pretty much fixed a good portion of my problem posted here:
hashTable::hashTable(const int n, char hFunction){
keys = 0;
hashFunction = hFunction;
tableSize = next_prime(n, VERBOSE);
cout << "Table size is: " << tableSize << "\n\n"; // for debugging
system("pause"); // for debugging
table = new linkedList<int>[tableSize];
I also changed my linkedList<int> **table to linkedList<int> *table. If anyone else needs any pointers on the rest of this NOW working hash function, just get a hold of me.
#include <iostream>
#include<string>
using namespace std;
struct nodeType
{
int info;
nodeType *next;
};
class linkedListType
{
private:
nodeType *first, *last;
int length;
public:
linkedListType()//constructor
{
first = last = NULL;
length = 0;
}
void print() // normal print
{
nodeType * current = first;
while (current != NULL)
{
cout << current->info <<" ";
// update statement
current = current ->next;
}
}
void insertEnd(int item) //insert item to the end of the list
{ // forward insertion
nodeType* newNode = new nodeType;
newNode ->info = item;
if (length == 0)
{
first = last = newNode;
newNode->next = NULL;
}//if
else
{
last->next = newNode;
last = newNode;
newNode->next = NULL;
}// else
length++;
}
}
void clearList()
{
nodeType * current;
while ( first != NULL)
{
current = first;
first = first->next;
delete current;
length--;
}// while
~linkedListType() //destroctor
{
clearList();
}
> `
//
Blockquote i cant write this method emplement please anyone help me and explane why ////////////////////////////////////////////////////////////////////
/this method. can anyone help ma to write it to me and explan why/
////////////////////////////////////////////////////////////////////
`
void printReverse() /*this is the function that i cant understand it or complete it. this function print elements in the list in reverse*/
{
nodeYype* current=last ,*newnode =new nodType ;
for(int i=length;i>=0;i--)
//i cant complete this method
}
};
void main()
{
linkedListType list1;
list1.insertEnd(12); //insert item
list1.insertEnd(25);//insert item
list1.insertEnd(18);//insert item
list1.insertEnd(37);//insert item
list1.insertEnd(60);//insert item
list1.insertEnd(100);//insert item
list1.insertEnd(37);//insert item
list1.insertEnd(37);//insert item
list1.insertEnd(37);//insert item
list1.insertEnd(60);//insert item
list1.insertEnd(25);//insert item
list1.insertEnd(100);//insert item
list1.insertEnd(25);//insert item
cout <<"Printing the linked list elements\n";
list1.print();
cout <<"\nPrinting the list elements in reverse order\n";
list1.printReverse();
}
void nodeType::PrintListReverse()
{
if (next)
next->PrintListReverse();
std::cout << info << std::endl;
}
Recursively find the end of the list, printing on return.
(I'm only enabling you because I'm bored)
Alternatively:
void linkedListType::PrintList()
{
std::vector<int> info(length);
nodeType* curNode = first;
for (int i = 0; curNode != NULL; i++, curNode = curNode->next)
{
info[i] = curNode->info;
}
for (int i = length-1; i >=0; i--)
{
std::cout << info[i] << std::endl;
}
}
If you can write a recursive function to traverse the list in proper order, printing it in reverse order is a snap.
There are two possibilities. Either to write a recursive function or rebuild your list in the reverse order. That is before printing the list you either create a new list on the base pf existent or rebuild the original list itself.
You already have a loop that decrements i from length to 0. Based on i, you can traverse the list and print the node that you reached. Fine tune for off by 1 errors so that you actually print from last to first and don't print when the list is empty.