I'm making a list in C++ from scratch, not using the STL list funciton. My program is designed for the user to insert a new item (string) to the list, one at a time. The items are supposed to be sorted as they are inserted, and it partially works. The user is supposed to be able to print them forwards and backwards.
Examples:
I insert: 1, 3, 2 - result forward: 1, 2, 3 - backwards: 3, 2, 1
I insert 1, 3, 2, 4 - result forward: 1, 4, 2, 3 - backwards: 3, 2, 4, 1
I insert 4, 2, 3 - result forward: 2, 3, 4 - backwards: 4, 3, 2
I insert 4, 2, 3, 1 - result forward: 1, 4 - backwards: 1, 3 repetedly until program crashes
These are a few examples, I could include more. I can not for the life of me see what's wrong wth my code. I have gotten help from people I know who are great coders, but they were unable to see the problem, after looking at it for a couple hours. I've been stuck at this for days now, and I just don't see it.
Here is my code (comments are in Norwegian, sorry!):
main.cpp
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
//definerer noden
struct node
{
string data; //det noden inneholder
node* next; //nestepeker
node* prev; //forrigepeker
};
//definerer funksjonene
bool isEmpty(node* first);
char menu();
void insertAsFirstElement(node* &first, node* &end, string data);
void insert(node* &first, node* &end, string data);
void remove(node* &first, node* &end, string data);
void showList(node* first);
void printBackwards(node* end);
//er noden tom?
bool isEmpty(node* first)
{
if(first == NULL)
return true;
else
return false;
}
//sender valgskjermen til konsollen
char menu()
{
char choice;
cout << "Welcome to LISTOMANIA 3000x! \n" << endl;
cout << "Press <1> to add an item" << endl;
cout << "Press <2> to remove item on top" << endl;
cout << "Press <3> to display the list forward" << endl;
cout << "Press <4> to display the list backwards" << endl;
cout << "Press <5> to exit" << endl;
cout << "\nInput: ";
cin >> choice;
return choice;
}
//hvis lista er tom, sett inn node som første element:
void insertAsFirstElement(node* &first, node* &end, string data)
{
cout << "temp is first\n";
node* temp = new node;
temp->data = data;
temp->next = NULL;
temp->prev = NULL;
first = temp;
end = temp;
}
//hvis lista ikke er tom, sett inn noden sortert:
void insert(node* &first, node* &end, string data)
{
if(isEmpty(first))
{
insertAsFirstElement(first, end, data);
}
else
{
node* temp = new node;
temp->data = data;
node* n = first;
while(n)
{
if(n->data > temp->data)
{
cout << "temp BEFORE n" << endl;
temp->prev = n->prev;
temp->next = n;
n->prev = temp;
if(temp->prev)
{
temp->prev->next = temp;
}
else
{
first = temp;
}
}
else if(n->data <= temp->data)
{
cout << "temp AFTER n" << endl;
//temp = new node;
//temp->data = data;
temp->prev = n;
temp->next = n->next;
n->next = temp;
if(temp->next)
{
temp->next->prev = temp;
}
else
{
end = temp;
}
break;
}
n = n->next;
}
}
}
//sletter valgt node
void remove(node* &first, node* &end, string data)
{
string delItem;
node* temp;
if(isEmpty(first))
cout << "\nNothing to delete, the list is empty!\n------------------------------------------------\n------------------------------------------------\n";
else if(first == end)
{
cout << "\nYou removed <" << first->data << ">!" << endl;
delete first;
first = NULL;
end = NULL;
cout <<"------------------------------------------------\n------------------------------------------------\n";
}
else
{
node* temp = first;
cout << "You removed <" << temp->data << ">!" << endl;
first = first->next;
delete temp;
cout <<"------------------------------------------------\n------------------------------------------------\n";
}
}
//skriver ut listen alfabetisk
void showList(node* first)
{
node * temp = first;
if(isEmpty(first))
{
cout << "\nThe list is empty!\n";
}
else
{
cout << "\nThe list contains: \n\n";
while(temp != NULL)
{
cout << temp->data << endl;
temp = temp->next;
}
}
cout << "------------------------------------------------\n";
cout << "------------------------------------------------\n";
}
//skriver ut listen omvendt alfabetisk
void printBackwards(node* end)
{
node * temp = end;
if(isEmpty(end))
{
cout << "\nThe list is empty!\n";
}
else
{
cout << "\nThe list contains: \n\n";
while(temp != NULL)
{
cout << temp->data << endl;
temp = temp->prev;
}
}
cout << "------------------------------------------------\n";
cout << "------------------------------------------------\n";
}
//mainfunksjon
int main()
{
node* first = NULL;
node* end = NULL;
char choice;
string data;
do
{
choice = menu();
switch(choice)
{
case '1': cout <<"\nPlease add something to the list: ";
cin >> data;
insert(first, end, data);
cout << "------------------------------------------------\n------------------------------------------------\n";
break;
case '2': remove(first, end, data);
break;
case '3': showList(first);
break;
case '4': printBackwards(end);
break;
case '5': cout << "\nSystem exit...\n";
break;
default: cout << "\nInvalid input!\n------------------------------------------------\n------------------------------------------------\n";
}
}while(choice != '5');
return 0;
}
Just ignore the lines of hyphens, they are just there to make the program look prettier when it is run.
Please note that I am a beginner! There might be lots of other mistakes too, other than my problem. Also ignore the remove function, as I haven't gotten to that problem yet...
check two lines that I added with comments //1.this line and //2.this line the fist one is called when temp<n so you have to compare temp with previous node of n, and the second one is for when temp>=n so you have to do is to compare temp with next node of n. with what I said so far it is clear that you have to remove the line that I commented with //4.you should remove this line : n = temp->next; this is what cause your last problem. Also you have another mistake, you have to remove the break; it leaves your listed in the middle of the sort so your sort never completed and that is what cause the other problem.
while(n)
{
if(n->data > temp->data)
{
cout << "temp BEFORE n" << endl;
temp->prev = n->prev;
temp->next = n;
n->prev = temp;
if(temp->prev)
{
temp->prev->next = temp;
}
else
{
first = temp;
}
n = temp->prev; //1.This line
}
else if(n->data <= temp->data)
{
cout << "temp AFTER n" << endl;
//temp = new node;
//temp->data = data;
temp->prev = n;
temp->next = n->next;
n->next = temp;
if(temp->next)
{
temp->next->prev = temp;
}
else
{
end = temp;
}
n = temp->next; //2.This line
//3.you should comment this line : break;
}
//4.you should remove this line : n = temp->next;
}
I got some help from more people, and we found a solution. Here is my insert fucntion:
//hvis lista ikke er tom, sett inn noden sortert:
void insert(node* &first, node* &end, string data)
{
if(isEmpty(first))
{
insertAsFirstElement(first, end, data);
}
else
{
node* temp = new node;
temp->data = data;
temp->next = first;
temp->prev = NULL;
first->prev = temp;
first = temp;
}
//sortering
if(first != NULL)
{
node* current = first;
node* prev = NULL;
node* tempNode = NULL;
while(current->next != NULL)
{
tempNode = current->next;
//cout << "current: " << current->data << " tempNode: " << tempNode->data << endl;
if(current->data > tempNode->data)
{
//cout << "swapped " << "current: " << current->data << " tempNode: " << tempNode->data << endl;
swap(current->data, tempNode->data);
}
else
{
prev = current;
current = current->next;
}
}
}
}
This sorts the data if it is a string, with a little bug on numbers, interpreted as a string, which can be solved with converting all numbers to an int.
EDIT:
That bug with the nubmers isn't really a bug at all. The list thinks 11 is smaller than 5, but that is because every input is interprated as a string. So then if you think that 1 = a and 2 = b, then it makes perfect sense that 11 < 5. So if you want them to be sorted how it would logically be done, having 11 > 5, you'd have to convert all numbers to an int.
Related
I am designing a Linked List where I can Insert and delete item from the list. But there is an issue inserting item at the end of linked list.
I thought my logic was fine for inserting an item at the end of linked list. But I am getting this (segmentation fault : core dumped) error when I am trying to insert item that should be inserted at the end of Linked List. Can Anyone help me with this issue
#include <iostream>
using namespace std;
struct list
{
int data;
list *next,*back;
};
typedef struct list node;
node *start = NULL;
void display()
{
node *temp;
temp = start;
while (temp!=NULL)
{
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
void insertion(int item)
{
node *temp,*temp2;
if(start == NULL)
{
start = new node();
start->data = item;
start->next = NULL;
}
else if(item <= start->data)
{
temp = new node();
temp->data = item;
temp->next = start;
start = temp;
}
else // this the logic for inserting middle and end of linked list
{
temp = start;
while(item >= temp->next->data && temp->next != NULL)
{
temp = temp->next;
}
temp2 = new node();
temp2->data = item;
temp2->next = temp->next;
temp->next = temp2;
}
}
void deletion()
{
}
void showMenu()
{
cout << "0.Exit\n1.ShowMenu\n2.Insert\n3.Delete\n4.Display" << endl;
}
int main()
{
showMenu();
int choice;
cout <<"Enter your Choice " << endl;
cin >> choice;
while(choice != 0)
{
if(choice == 1)
{
showMenu();
}
else if(choice == 2)
{
int item;
cout << "Enter your item " << endl;
cin >> item;
insertion(item);
}
else if(choice == 3)
{
deletion();
}
else if(choice == 4)
{
display();
}
else
{
choice = 0;
}
cout <<"Enter your Choice " << endl;
cin >> choice;
}
return 0;
}
I have a LinkedList class and everything works except for my remove function. It works except for when it is removing from the end. If I remove from the end and then try to display the new list the program crashes and doesnt give me an error. I was wondering if someone could help me pinpoint what I did wrong in the remove function where I am removing the tail.
Main method
#include "LinkedList.h"
#include <cstdlib>
#include <iomanip>
using namespace std;
void MainMenu(int& menu);
int main(int argc, char** argv) {
int menu = 0;
string name;
LinkedList list;
while (true)
{
MainMenu(menu);
if (menu == 1)
{
cout << "Please enter the name you want to add to the front: " << endl;
cin >> name;
list.addFront(name);
}
else if (menu == 2)
{
cout << "Please enter the name you want to add to the back: " << endl;
cin >> name;
list.addBack(name);
}
else if (menu == 3)
{
cout << "Please enter the name you want to remove: " << endl;
cin >> name;
list.remove(name);
}
else if (menu == 4)
{
list.display();
}
else if (menu == 5)
{
cout << "\nThank you for using my program!" << endl;
exit(0);
}
}
return 0;
}
void MainMenu(int& menu)
{
cout << '\n' << endl;
cout << left << setw(30) << right << setw(20) << "Main Menu" << endl;
cout << setw(36) << setfill('*') << "\n" << endl;
cout << "1. Add node to front." << endl;
cout << "2. Add node to back." << endl;
cout << "3. Remove node." << endl;
cout << "4. Display list." << endl;
cout << "5. Exit" << endl;
cout << setw(36) << "\n" << endl;
cout << "Please enter a menu number to proceed: " << endl;
cin >> menu;
while (menu != 1 && menu != 2 && menu != 3 && menu != 4 && menu != 5)
{
cout << "Menu options are 1 - 5" << endl;
cout << "Please enter a menu number to proceed: " << endl;
cin.clear();
cin.ignore(100, '\n');
cin >> menu;
}
cout << setfill(' ') << "\n" << endl;
}
Header file
#include <iostream>
using namespace std;
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
struct Node
{
string name;
Node * next;
};
class LinkedList {
public:
Node * head = nullptr;
Node * tail = nullptr;
Node * current = nullptr;
void addFront(string name);
void addBack(string name);
void remove(string name);
void display();
LinkedList();
LinkedList(const LinkedList& orig);
virtual ~LinkedList();
private:
};
#endif /* LINKEDLIST_H */
Source File
#include "LinkedList.h"
void LinkedList::addFront(string name)
{
Node * node = new Node();
node->name = name;
if (head != nullptr)
{
node->next = head;
head = node;
}
else
{
head = node;
tail = node;
}
}
void LinkedList::addBack(string name)
{
Node * node = new Node();
node->name = name;
node->next = nullptr;
if (head == nullptr)
{
head = node;
tail = node;
}
else
{
node->next = nullptr;
tail->next = node;
tail = node;
}
}
void LinkedList::remove(string name)
{
Node * temp = head;
while (temp != nullptr)
{
if (temp->name == name)
{
cout << "Name found! Being removed." << endl;
break;
}
temp = temp->next;
if (temp == nullptr)
{
cout << "Name not found!" << endl;
return;
}
}
temp = head;
if(head == nullptr)
{
cout << "The list is empty." << endl;
return;
}
while(!(temp->name == name))
{
temp = temp->next;
}
if (temp == tail && temp == head)
{
head = nullptr;
tail = nullptr;
delete temp;
}
else if (temp == tail)
{
temp->next = tail;
delete temp->next;
temp->next = nullptr;
tail = temp;
}
else if(temp == head)
{
temp = head;
head = temp->next;
delete temp;
}
else
{
temp = head;
while(!(temp->next->name == name))
{
temp = temp->next;
}
Node * next = temp->next->next;
delete temp->next;
temp->next = next;
}
}
void LinkedList::display()
{
current = head;
if (current == nullptr)
{
cout << "The list is empty!" << endl;
}
while (current != nullptr)
{
cout << current->name << endl;
current = current->next;
}
}
LinkedList::LinkedList() {
}
LinkedList::LinkedList(const LinkedList& orig) {
}
LinkedList::~LinkedList() {
}
Your main problem is this section here
else if (temp == tail)
{
temp->next = tail;
delete temp->next;
temp->next = nullptr;
tail = temp;
}
That is what executes if the match is the last item. But if it is the last item then temp->next will be tail because you just set it to tail, and since temp == tail that also invalidates temp. Setting temp->next will be using a deleted pointer. There's no fixing this at this point because you need the previous node to set tail to, and you didn't save it, so you'd have to loop through again to get it.
Now, for the solution, you should do a single loop. No need to loop multiple times (3 in most cases)
void LinkedList::remove(string name)
{
Node * temp = head;
Node * prev = nullptr;
while (temp != nullptr)
{
if (temp->name == name)
{
cout << "Name found! Being removed." << endl;
if (prev != nullptr) {
prev->next = temp->next
}
else {
head = temp->next;
}
if (tail == temp) {
tail = prev;
}
delete temp;
return;
}
prev = temp;
temp = temp->next;
}
cout << "Name not found!" << endl;
}
For starters everywhere in member function declarations where a parameter is declared like
string name
you should change it to
const string &name
Secondly the member function remove shall not issue any message. It is the caller of the function that decides whether to output a message.
Your function is inefficient because it traverses the list two or even three times in loops and has too many conditions that makes the function too complicated. As a result the function has bugs.
For example in this if statement
else if (temp == tail)
{
temp->next = tail;
delete temp->next;
temp->next = nullptr;
tail = temp;
}
there is used deleted pointer temp to access memory because temp is equal to tail (according to the condition of the if statement)
temp->next = nullptr;
and tail again is set to the deleted pointer
tail = temp;
The function can be declared and defined the following way
class LinkedList {
public:
//...
bool remove( const std::string &name );
};
bool LinkedList::remove( const std::string &name )
{
Node *prev = nullptr;
Node *current = head;
while ( current && current->name != name )
{
prev = current;
current = current->next;
}
bool success = current != nullptr;
if ( success )
{
if ( prev )
{
prev->next = current->next;
if ( prev->next == nullptr ) tail = prev;
}
else
{
head = head->next;
if ( head == nullptr ) tail = nullptr;
}
delete current;
}
return success;
}
I've been writing a program using a linked list, but for some reason my program is making a false node at the start of the program that is messing with everything else
this file controls the functions in the header file
Node *createNode() {
Node *newNode = new Node;
cout << "Enter in Students last Name" << endl;
cin >> newNode->lastName;
cout << "Enter in Students first Name" << endl;
cin >> newNode->firstName;
cout << "Enter in Students id" << endl;
cin >> newNode->idNumber;
return newNode;
}
Node *insertNode(Node *ptr) {
Node *newNode = createNode();
if( ptr == NULL ) {
ptr = newNode;
} else if ( ptr->idNumber > newNode->idNumber ) {
newNode->next = ptr;
ptr = newNode;
} else {
Node *temp = ptr;
while( temp->next != NULL &&
temp->next->idNumber < newNode->idNumber )
temp = temp->next;
if( temp->next == NULL ) {
temp->next = newNode;
} else {
newNode->next = temp->next;
temp->next = newNode;
}
}
return ptr;
}
Node *searchNode(Node *ptr, int id) {
Node *temp;
Node *found;
bool isfound = false;
temp = ptr;
if(temp == NULL) {
cout << "There are no students in the list" << endl;
isfound = true;
}
while( isfound != true && temp->next != NULL ) {
if( temp->idNumber == id ) {
found = temp;
isfound = true;
cout << found->lastName << ", " << found->firstName
<< ": " << found->idNumber << endl;
} else {
temp = temp->next;
}
}
return found;
}
void printList( Node *ptr ){
Node *temp = ptr;
while( temp != NULL ) {
cout << temp->lastName << ", "
<< temp->firstName<< ": "
<< temp->idNumber << endl;
temp = temp->next;
}
}
and this is the main file where the program is executed
int main() {
Node *list = new Node();
displayList(list);
return 0;
}
void displayList( Node *node ) {
int option = -1;
cout << node->idNumber << endl;
while( option != 5 ) {
cout << endl;
cout << "What do you want to do?" << endl;
cout << "1: Add a student" << endl;
cout << "2: Search for student" << endl;
cout << "3: Delete Student" << endl;
cout << "4: Print Student List" << endl;
cout << "5: Exit" << endl;
cout << "Enter a number for the choice: ";
cin >> option;
if( cin.fail() || option > 5 || option < 0 ) {
cin.clear();
cin.ignore();
option = -1;
}
switch( option ) {
case 1:{
insertNode(node);
}
break;
case 2:{
if(node != NULL){
cout<<"Enter the id you want to find: ";
int sid;
cin >> sid;
searchNode(node, sid);
} else {
cout<<"No Ids in the list"<<endl;
}
}
break;
case 4: printList(node);
break;
case 5: cout<<"GoodBye."<<endl ;
break;
default: cout<<"you have entered a invalid character"<<endl;
}
}
}
this is what is being created before a new node is even created
What do you want to do?
1: Add a student
2: Search for student
3: Delete Student
4: Print Student List
5: Exit
Enter a number for the choice: 4
, : 0
Node *list = new Node(); since you created a new Node in main and passing a valid Node address to displayList( Node *node ); and then to printList( Node *ptr ), its printing the zero initialized Node data.
You can change Node *list = new Node(); to Node *list = NULL in main()
Remove cout << node->idNumber << endl; in displayList( Node *node ); otherwise you will be getting segmentation fault or null dereferencing.
In Node *createNode(), add newNode->next = 0; you must set the next pointer of newly created Node to NULL.
In Node *searchNode(Node *ptr, int id) change while( isfound != true && temp->next != NULL ) into while( isfound != true && temp != NULL ), otherwise it will not search the last node.
Store the return value of insertNode(node) to node in displayList( Node *node ); as node = insertNode(node) otherwise you are loosing the newly added node for both the if and else if cases of insertNode
I had a circular link list which has add, delete, printlist and search functions etc. All the functions works correctly but when I delete all nodes in the list and than try to add new nodes to the same list, I get project.exe has triggered a breakpoint message.
List.h
#ifndef LIST_H
#define LIST_H
using namespace std;
class list {
public:
struct node {
string data, assignee, date;
node *next;
};
typedef struct node NodePtr;
NodePtr *head, *current, *temp, *dummy;
list();
void add();
void del();
void printList();
void menu();
void exit();
void search();
};
#endif
Source.cpp
#include <cstdlib>
#include <iostream>
#include "List.h"
#include<string>
using namespace std;
list::list() { //constructor
head = NULL;
current = NULL;
temp = NULL;
}
void list::add(){
string addTask, addAssignee, addDate;
NodePtr *newNode = new NodePtr;
//entering the data of the tasks
cout << "Enter the name of the task:\n"<<"<<";
getline(cin, addTask); // compailer doesnt detect the first getline function, ı dont understan why. ı had to put it twice
getline(cin, addTask);
cout << "Enter the assignee name for the task:\n" << "<<";
getline(cin, addAssignee);
cout << "Enter the deadline for the task:\n" << "<<";
getline(cin, addDate);
cout << "\n";
//assignt data to the new node
newNode->data = addTask;
newNode->assignee = addAssignee;
newNode->date = addDate;
newNode->next = NULL;
if (head != NULL){
current = head;
while (current->next != head){ //finding the last node
current = current->next;
}
current->next = newNode;
dummy = newNode;
dummy->next = head; // we make the list, circular
}
else //here will work if the list is empty
{
head = newNode;
dummy = newNode;
head->next=head;
}
}
void list::printList(){
int i = 1;
current = head;
if (head == NULL){
cout << "List is empty\n\n";
}
else
{
do
{
cout << i << "-";
cout << current->data << endl;
cout << current->assignee << endl;
cout << current->date << endl << endl;
current = current->next;
i++;
} while (current != dummy->next);
}
}
void list::del(){ //tüm liste silindikten sonra tekrar işlem(ekleme, listeleme etc.) yapılamıyor hata veriyor
NodePtr *delPtr;
delPtr = NULL;
int ID;
cout << "These tasks exist in the list:\n";
printList();
cout << "Choose the ID of the task you want to remove:\n";
cin >> ID;
if (head == NULL){
cout << "List does not includes any task.\n";
}
else
if (ID == 1){
delPtr = head;
head = head->next;
delete delPtr;
dummy->next = head;
}
else
{
current = head;
for (int k = 1; k <= ID - 1; k++){
temp = current;
current = current->next;
}
if (current == dummy){
dummy = temp;
dummy->next = head;
}
delPtr = current;
current = current->next;
temp->next = current;
delete delPtr;
}
}
void list::menu(){
cout << "Choose an operation\n"
<< "A: Add Task\n"
<< "S: Search for Task\n"
<< "L: List All Tasks\n"
<< "R: Remove Task\n"
<< "E: Exit\n\n"<<"<<";
}
void list::search(){
string searchTask;
NodePtr *search;
search = head;
cout << "To search for a task, enter its task name or assignee name:\n" << "<<";
getline(cin, searchTask);
getline(cin, searchTask);
while (search != dummy){//bu satır problemli gibi gözüküyor
if (search->data == searchTask || search->assignee == searchTask){
cout << search->data << endl
<< search->assignee << endl
<< search->date << endl<<endl;
}
search = search->next;
}
}
void list::exit(){
node *delPtr;
current = head;
if (head != NULL){
do{
temp = current;
delPtr = temp;
current = current->next;
delete delPtr;
} while (current != dummy);
}
}
Main.cpp
#include <cstdlib>
#include <iostream>
#include "List.h"
#include<string>
using namespace std;
int main(){
char operation;
list tasks;
tasks.menu();
cin >> operation;
while (operation!='E' && operation!='e'){
switch (operation)
{
case 'A':case'a':
tasks.add();
break;
case 'S': case's':
tasks.search();
break;
case 'L': case 'l':
cout << "All tasks are listed below:\n";
tasks.printList();
break;
case 'R': case 'r':
tasks.del();
break;
default:
break;
}
tasks.menu();
cin >> operation;
}
tasks.exit();
return 0;
}
I'm currently learning Linked Lists in C++, and I can't write a print function which prints out the elements of the list; I mean I wrote the function but it doesn't work properly.
#include <iostream>
using namespace std;
struct node
{
char name[20];
node* next;
};
node* addNewPerson(node* head)
{
node* person = new node;
cout << "Name: ";
cin >> person->name;
person->next = NULL;
if (head == NULL) //is empty
{
head = person;
}
else
{
person = person->next;
}
return head;
}
void printList(node* head)
{
node* temp = head;
cout << temp->name << endl;
}
int main()
{
node* head = NULL;
node* temp = head;
unsigned short people = 0;
cout << "How many people do you want to invite to the party?" << endl;
cout << "Answer: ";
cin >> people;
cout << endl;
for (unsigned short i = 1; i <= people; i++)
{
addNewPerson(head);
cout << endl;
}
cout << "LIST: " << endl;
cout << endl;
while (temp != NULL)
{
printList(temp);
temp = temp->next;
}
cin.get();
}
I am wondering what I'm doing wrong, please help me!
It is obvious that function addNewPerson is wrong.
node* addNewPerson(node* head)
{
node* person = new node;
cout << "Name: ";
cin >> person->name;
person->next = NULL;
if (head == NULL) //is empty
{
head = person;
}
else
{
person = person->next;
}
return head;
}
You allocated new node person.
node* person = new node;
Set its field next to NULL
person->next = NULL;
Then if head is not equal to NULL you set person to person->next
person = person->next;
As person->next was set to NULL it means that now also person will be equal to NULL.
Moreover the function returns head that can be changed in the function. However you ignore returned value in main
addNewPerson(head);
At least there should be
head = addNewPerson(head);
The valid function addNewPerson could look the following way
node* addNewPerson(node* head)
{
node* person = new node;
cout << "Name: ";
cin >> person->name;
person->next = head;
head = person;
return head;
}
And in main you have to write
for (unsigned short i = 1; i <= people; i++)
{
head = addNewPerson(head);
cout << endl;
}
Function printList does not output the whole list. It outputs only data member name of the first node that is of head.
void printList(node* head)
{
node* temp = head;
cout << temp->name << endl;
}
It should look the following way
void printList(node* head)
{
for ( ; head; head = head->next )
{
cout << head->name << endl;
}
}
And at last main should look as
int main()
{
node* head = NULL;
unsigned short people = 0;
cout << "How many people do you want to invite to the party?" << endl;
cout << "Answer: ";
cin >> people;
cout << endl;
for ( unsigned short i = 0; i < people; i++ )
{
head = addNewPerson(head);
cout << endl;
}
cout << "LIST: " << endl;
cout << endl;
printList( head );
cin.get();
}
In your addNewPerson function person->next never gets set, because head is always NULL.
addNewPerson method
Your addNewPerson method never added a new person to the list it just set the head to the new person.
node* addNewPerson(node* head)
{
node* person = new node;
cout << "Name: ";
cin >> person->name;
person->next = NULL;
if (head->next == NULL) //is empty
{
head->next = person;
}
else
{
person->next = head->next;
head->next = person;
}
return head;
}
printList method
Your method printList should do what it says and print the list, instead of just printing one person at a time.
void printList(node* head)
{
node* tmp = head;
while(tmp->next != NULL) {
tmp = tmp->next;
cout >> tmp->name >> endl;
}
}
main method
Upadted your main method with the new printList method.
int main()
{
node* head = new node;
unsigned short people = 0;
cout << "How many people do you want to invite to the party?" << endl;
cout << "Answer: ";
cin >> people;
cout << endl;
for (unsigned short i = 1; i <= people; i++)
{
addNewPerson(head);
cout << endl;
}
cout << "LIST: " << endl;
cout << endl;
cout << printList(head);
cin.get();
}
Also why are you using unsigned short and char arrays? Do you have a limited amount of memory? Why not just use int and string?
When you are adding a new person, it is not actually put into the linked list, since you have never invoked something like head -> next = person.
The section in your addNewPerson routine should be something like
if (head == NULL) {
head = person;
} else {
node * end = head;
while (end -> next != NULL) // find the end of the list to insert new person
end = end -> next;
end -> next = person;
}
And in the beginning you can't just pass head into addNewPerson, since it is a pointer with null value, the addNewPerson method accepts a pointer by value (value of the memory address it is pointing at) rather than a reference to head. So you need to use
node* addNewPerson(node* &head) { ... }
instead. Finally, when you declare temp, it first receives the value of head as well, so later access to temp would only give you NULL again. You need to change it to
node* &temp = head;
I think the problem is in how the link list is being added to in addNewPerson.
The input to addNewPerson is 'head' so each time, before adding a new node to the linked list, we need to traverse all the way down the linked list till the last node before appending 'person' to the linked list.
struct node
{
char name[20];
node* next;
};
node* addNewPerson(node* head)
{
node* person = new node;
//cout << "Name: ";
cin >> person->name;
person->next = head;
head = person;
return head;
}
void PrintLL(node *head)
{
while (head!=NULL){
cout<< head->name <<endl;
head=head->next;
}
}
int main() {
node* head = NULL;
node* temp = head;
int num_ppl;
cout << "How many people do you want to invite to the party?" << endl;
cout << "Answer: ";
cin >> num_ppl;
for(int arr_i = 0; arr_i < num_ppl; arr_i++){
head = addNewPerson(head);
}
PrintLL(head);
return 0;
}