case 1 work fine but case 2 and 3 just stop the loop and the program
and i cannot choose any other case after that as! i wonder why it stop the loop from going as choice here would never equal 0 which i believe it's the only reason would stop the loop from going forward! thanks in advance.
i also checked the functions and all of them seems fine to me i'm not sure if the problem could be with them
#include "stdafx.h"
#include <iostream>
using namespace std;
void insert_node(int new_data);
void print_node();
void delete_node();
int new_data;
char choice;
struct node {
int data;
node* next;
};
node* head = NULL;
void main()
{
do
{
cout << "Enter 1 to insert a new node \n";
cout << "Enter 2 to disply the list \n";
cout << "Enter 3 to delete the last node \n";
cin >> choice;
switch (choice)
{
case '1':
cout << "Enter the data \n";
cin >> new_data;
insert_node(new_data);
break;
case '2':
if (head != NULL)
print_node();
else
cout << "SORRY, your list is empty \n";
break;
case '3':
delete_node();
break;
default:
cout << "Invalid entry \n";
}
} while (choice != '0');
}
void insert_node(int new_data)
{
node* NewNode = new node;
NewNode->data = new_data;
if (head == NULL)
head = NewNode;
else
{
NewNode->next = head;
head = NewNode;
}
}
void print_node()
{
node* printer=head;
do
{
cout << printer->data<<" - ";
printer = printer->next;
} while (printer != NULL);
}
void delete_node()
{
if (head == NULL)
cout << "no node to be deleted \n";
else
{
node* curr = head;
node* prev = NULL;
while (curr->next != NULL)
{
prev = curr;
curr = curr->next;
}
if (prev == NULL)
{
delete(curr);
head = NULL;
return;
}
prev->next = NULL;
delete(curr);
}
}
This is bugged
void insert_node(int new_data)
{
node* NewNode = new node;
NewNode->data = new_data;
if (head == NULL)
head = NewNode;
else
{
NewNode->next = head;
head = NewNode;
}
}
it should be
void insert_node(int new_data)
{
node* NewNode = new node;
NewNode->data = new_data;
NewNode->next = head;
head = NewNode;
}
Your version fails to set next when adding the first node to the list. And as you can see there's no need to make head == NULL a special case.
Because you aren't creating the list correctly in the first place, any attempt to print or delete items from the list is likely to fail.
And your print_node function would fail on an empty list. It should be a while loop not a do ... while loop.
void print_node()
{
node* printer=head;
while (printer != NULL)
{
cout << printer->data<<" - ";
printer = printer->next;
}
}
Your delete_node function looks very suspicious to me as well.
Related
I don't know where I'm going wrong. Output shows 1 upon inputting 1 2 3 -1 (-1 to terminate insertion of nodes). Help is appreciated!
I can't seem to find the error in my code that is resulting in wrong output upon different test cases.
Other approaches to the same problem are also welcome.
Any tips so that i won't commit such errors in the future, along with some fundamentals(generally tips) of linked lists
#include <iostream>
using namespace std;
class Node
{
public:
int data;
Node *next;
Node(int data)
{
this->data = data;
next = NULL;
}
};
Node *insert()
{
int data;
cin >> data;
Node *head = NULL;
Node *tail = NULL;
while (data != -1)
{
Node *n = new Node(data);
if (head == NULL)
{
head = n;
tail = n;
}
else
{
tail->next = n;
tail = tail->next;
}
cin >> data;
}
return head;
}
void print(Node *head)
{
Node *temp = head;
while (temp != NULL)
{
cout << temp->data << " ";
temp = temp->next;
}
}
Node *rev_LL(Node *head)
{
if (head == NULL || head->next == NULL)
{
return head;
}
Node *smallAns = rev_LL(head->next);
Node *temp = smallAns;
while (temp->next != NULL)
{
temp = temp->next;
}
temp->next = head;
head->next = NULL;
return smallAns;
}
int main()
{
Node *head = insert();
print(head);
cout << endl;
cout << "After reversing the Linked list : " << endl;
rev_LL(head);
print(head);
cout << endl;
return 0;
}
You have to assign the return value of rev_LL to head instead of just ignoring that.
int main()
{
Node *head = insert();
print(head);
cout << endl;
cout << "After reversing the Linked list : " << endl;
//rev_LL(head);
head = rev_LL(head); // assign the result
print(head);
cout << endl;
return 0;
}
when i am inserting node in the beginning of the linked list, node is inserted in the beginning and is displayed. if i call display separately then it does not work and for inserting node at specific loc and at the end, calling display function works well.
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
typedef struct node {
int data;
struct node* next;
} node;
node* create(int n)
{
node* temp = NULL;
node* head = NULL;
node* p;
int i;
for (i = 0; i < n; i++) {
temp = (node*)malloc(sizeof(node));
cout << "enter the data for node number " << i << endl;
cin >> temp->data;
temp->next = NULL;
if (head == NULL) {
head = temp;
}
else {
p = head;
while (p->next != NULL) {
p = p->next;
}
p->next = temp;
}
}
return head;
}
node* insertatbeg(node* head)
{
node* temp = NULL;
temp = (node*)malloc(sizeof(node));
cout << "\nenter the data for first node" << endl;
cin >> temp->data;
temp->next = head;
head = temp;
return head;
}
void display(node* head)
{
node* t = NULL;
t = head;
while (t != NULL) {
cout << t->data << "->";
t = t->next;
}
}
node* insertatspecloc(node* head)
{
int n;
node* temp = NULL;
node* t = head;
temp = (node*)malloc(sizeof(node));
cout << "enter the data of node after which you want to insert the
node "<<endl;
cin
>> n;
cout << "\nenter the data for last node" << endl;
cin >> temp->data;
while (t->data != n) {
t = t->next;
}
temp->next = t->next;
t->next = temp;
return head;
}
node* insertatend(node* head)
{
node* temp = NULL;
temp = (node*)malloc(sizeof(node));
cout << "\nenter the data for last node" << endl;
cin >> temp->data;
temp->next = NULL;
node* q;
q = head;
while (q->next != NULL) {
q = q->next;
}
q->next = temp;
return head;
}
int main()
{
int n, a;
struct node* head = NULL;
cout << "enter the number of nodes u want to add";
cin >> n;
head = create(n);
display(head);
cout << "\npress 1 to add node at the beginning";
cout << "\npress 2 to add node at the specific location";
cout << "\npress 3 to add node at the end\n";
cin >> a;
if (a == 1) {
insertatbeg(head);
cout << "\nlinked list after insertion:\n";
display(head);
}
if (a == 2) {
insertatspecloc(head);
cout << "\nlinked list after insertion:\n";
display(head);
}
if (a == 3) {
insertatend(head);
cout << "\nLinked list after insertion:\n";
display(head);
}
}
When you are calling insertatbeg(head); the copy of head pointer is passed as the argument of your function, then in function you are modyfing local variable (copy of head)
node *insertatbeg(node *head)
{
node *temp=NULL;
temp=(node*)malloc(sizeof(node));
cout<<"\nenter the data for first node"<<endl;
cin>>temp->data;
temp->next=head;
head=temp; // assign to local variable <---
return head;
}
and for this reason after executing insertatbeg head is not updated. insertatbeg returns pointer so you can resolve your issue by calling
head = insertatbeg(head);
or you can call function in above line without assigning but then you should pass head by reference to be able to modify original passed object in function:
node *insertatbeg(node *& head) // pass pointer by reference
{
node *temp=NULL;
//...
head = temp; // now it works
I am new to linked lists, and now I face a problem on how to add the node into the middle of a list. Example like if I got a name list show below and when I add data one by one just like below sequence:
1.andrew
2.eric
3.madness
4.gerik
I want my data "gerik" in "madness" place when it show out. I am able to sort the data infront of "eric" but after "eric" i am not idea. I want my output just like below:
1.andrew
2.eric
3.gerik
4.madness
Below will be my example code, please help me by giving me advise or code sample:
#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
using namespace std;
struct node
{
char f_name[20];
char l_name[20];
char u_id[10];
node *next;
};
node *head;
node *curr;
//prototype
void display();
void add();
void search_name();
void insert_data(node *tempnode);
void insert_before_head(node *tempnode);
void menu(char choice);
char pause;
//function start...
void search_name()
{
char name[20];
curr = head;
cin.ignore(30,'\n');
cout<<"Key In Last Name :"<<endl;
cin.get(name, 20);
cin.ignore(30,'\n');
while((curr->next != NULL) && (strcmp(curr->l_name, name) != 0))
{
curr = curr->next;
}
if(curr != NULL)
{
cout<<"Record Found !"<<endl;
cout<<"First Name"<<setw(16)<<"Last Name"<<setw(16)<<"User ID"<<endl;
cout<<"--------------------------------------------------------------"<<endl;
cout<<curr->f_name<<setw(20)<<curr->l_name<<setw(16)<<curr->u_id<<endl<<endl;
}
else
{
cout<<"No Match !"<<endl;
cout<<"Press 'Enter' To Continue"<<endl;
cin.get(pause = getch());
system("cls");
}
};
void display()
{
curr = head;
if(head != NULL)
{
cout<<"First Name"<<setw(16)<<"Last Name"<<setw(16)<<"User ID"<<endl;
cout<<"--------------------------------------------------------------"<<endl;
while(curr != NULL)
{
cout<<curr->f_name<<setw(20)<<curr->l_name<<setw(16)<<curr->u_id<<endl;
curr = curr->next;
}
}
else
{
cout<<"No Data. File storage Empty!"<<endl;
}
};
void add()
{
node *temp;
temp = new node;
cin.ignore(30, '\n');
cout<<"Key In First Name:"<<endl;
cin.get(temp->f_name, 20);
cin.ignore(30, '\n');
cout<<"Key In Last Name:"<<endl;
cin.get(temp->l_name, 20);
cin.ignore(30, '\n');
cout<<"Key In Your ID:"<<endl;
cin.get(temp->u_id, 10);
insert_data(temp);
};
void insert_data(node *tempnode)
{
node *temp;
if(head == NULL)
{
node *temp;
temp = new node;
temp = head;
tempnode->next = NULL;
head = tempnode;
}
else if(strcmp(tempnode->l_name, head->l_name) < 0)
{
insert_before_head(tempnode);
}
else
{
temp = new node;
curr = head;
while(curr->next != NULL)
{
curr = curr->next;
}
temp = tempnode;
curr->next = tempnode;
tempnode->next = NULL;
}
};
void insert_before_head(node *tempnode)
{
node *temp;
if(head != NULL)
{
temp = new node;
temp = tempnode;
tempnode->next = head;
head = tempnode;
}
};
void menu(int choice)
{
switch (choice)
{
case 1 :
add();
break;
case 2:
display();
break;
case 3:
search_name();
break;
case 4:
cout<<"Exit Program !"<<endl;
break;
default :
cout<<"Error! Program Terminate !"<<endl;
}
};
int main()
{
int choice;
node *temp;
head = NULL;
curr = NULL;
cout << "Data Stack Head And Any Position !" << endl;
system("cls");
do{
cout<<"1. Add Data."<<endl;
cout<<"2. Show Data. "<<endl;
cout<<"3. Search Last Name "<<endl;
cout<<"4. Exit. "<<endl;
cin >>choice;
menu(choice);
}while(choice != 4);
return 0;
}
To sort linked lists you need to use the divide and conquer strategy with merge sort.
In order to insert in the middle you need to create 2 nodes Node slow and Node fast. At first Node slow is head.next, Node fast is head.next.next and you keep moving those 2 by doing slow = slow.next and fast = fast.next.next, until you hit the end with Node fast. If you think about it, fast will be moving twice as fast as Node slow, so in the end Node slow will be in the middle. Then insert after that node.
We want to insert in our list newNode.
Let node X be the node, after which newNode should be inserted to preserve sorting order.
You can rewite your insert_data(...) function like in my example.
I took the code, sugested by WhozCraug and rewrote it to be more evident.
void insert_data(node *newNode)
{
node **pointerToTheNextPtr = &head;
// find position to insert new node
while (*pointerToTheNextPtr && strcmp((*pointerToTheNextPtr)->l_name, newNode->l_name) < 0)
pointerToTheNextPtr = &((*pointerToTheNextPtr)->next);
// here pointerToTheNextPtr stores the pointer to the X->next field
// insert new node between X and *(X->next)
newNode->next = *pointerToTheNextPtr; // set newNode->next = X->next
*pointerToTheNextPtr = newNode; // set X->next = newNode
}
Trying to create Lined List. I am having problem in the deleteNode function created in LinkedList.cpp file. Experiencing given error
Unhandled exception at 0x00D04C3C in LinkedList.exe: 0xC0000005:
Access violation reading location 0x00000004.
previous->link = temp->link;
LinkedList.h file
class Node
{
public:
int data;
Node *link;
};
class LList
{
private:
Node *Head, *Tail;
//void recursiveTraverse(Node *);
public:
LList();
~LList();
void create();
Node *getNode();
void append(Node *);
void insert(Node *, int);
void rtraverse();
void deleteNode(int);
void display();
};
LinkedList.cpp
#include "stdafx.h"
#include "LinkedList.h"
#include <iostream>
using namespace std;
LList::LList()
{
Head = nullptr; Tail = nullptr;
}
LList::~LList()
{
Node *Temp;
while (Head != nullptr)
{
Temp = Head;
Head = Head->link;
delete Temp;
}
}
void LList::create()
{
char choice;
Node *newNode = nullptr;
while (5)
{
cout << "Enter Data in the List (Enter N to cancel) ";
cin >> choice;
if (choice == 'n' || choice == 'N')
{
break;
}
newNode = getNode();
append(newNode);
}
}
Node *LList::getNode()
{
Node *temp = new Node;
//cout << "Enter Data in the List";
cin >> temp->data;
temp->link = nullptr;
return temp;
}
void LList::append(Node *temp)
{
if (Head == nullptr)
{
Head = temp;
Tail = temp;
}
else
{
Tail->link = temp;
Tail = temp;
}
}
void LList::display()
{
Node *temp = Head;
if (temp == nullptr)
{
cout << "No Item in the List" << endl;
}
else
{
while (temp != nullptr)
{
cout << temp->data << "\t";
temp = temp->link;
}
cout << endl;
}
}
void LList::insert(Node *newNode, int position)
{
int count = 0; Node *temp, *previous = nullptr;
temp = Head;
if (temp == nullptr)
{
Head = newNode;
Tail = newNode;
}
else
{
while (temp == nullptr || count < position)
{
count++;
previous = temp;
temp = temp->link;
}
previous->link = newNode;
newNode->link = temp;
}
}
void LList::deleteNode(int position)
{
int count = 1; Node * temp, *previous = nullptr;
temp = Head;
if (temp == nullptr)
{
cout << "No Data to delete." << endl;
}
else
{
while (count <= position + 1)
{
if (position == count + 1)
{
count++;
previous = temp;
previous->link = temp->link;
}
else if (count == position + 1)
{
count++;
previous->link = temp->link;
}
count++;
temp = temp->link;
}
}
}
Main.cpp goes here
I see multiple things wrong here, any one of which could be causing your problem. If they don't fix it I could take another look if someone else doesn't get to it first.
First and foremost, your if statements in your delete function will always execute. Because you are assigning instead of checking for equality, ie '=' instead of '=='. This alone may fix the issue.
The other thing that jumps out of the page is that you are obviously dynamically allocating each node, and your delete function should be delete'ing the memory once you are done with it.
Fix those two first and then see where you are at.
Looks like temp cannot be a nullpointer at the line giving an error, but previous might be.
Important: Note that the line
else if (count = position + 1)
Is actually an assignment. You probably meant
else if (count == position + 1)
The same goes for the if statement before that.
Cheers!
I am writing a three file C++ program for my class. This program is ordered linked list. The program compiles but crashes when I attempt to insert (Run the program, select choice press enter, type an int to insert and press enter). Any help would be greatly appreciated.
Driver File:
#include "SortedLinkedList.h"
#include <iostream>
using namespace std;
int displayMenu();
void proccessChoice(int, SortedLinkedList&);
int main()
{
SortedLinkedList sSList;
int choice = displayMenu();
do
{
if (choice != 3)
{
proccessChoice(choice, sSList);
}
} while (choice != 3);
return 0;
}
void proccessChoice(int input, SortedLinkedList& l)
{
switch(input)
{
case 1:
int num;
cout << "Please enter a int: ";
cin >> num;
l.addItem(num);
break;
case 2:
l.popFirst();
break;
}
}
int displayMenu()
{
int choice;
cout << "menu" << endl;
cout << "===========" << endl;
cout << "1. add an int" << endl;
cout << "2. Show Sorted Linked List" << endl;
cout << "3. Exit" << endl;
cin >> choice;
cin.ignore();
return choice;
}
Declaration File:
struct sslNode
{
sslNode* next;
int item;
};
class SortedLinkedList
{
private:
sslNode* head;
bool isEmpty ();
public:
SortedLinkedList();
~SortedLinkedList();
void addItem(int);
int popFirst();
};
Implementation File:
#include <iostream>
using namespace std;
#include "SortedLinkedList.h"
SortedLinkedList::SortedLinkedList()
{
head = NULL;
}
SortedLinkedList::~SortedLinkedList()
{
sslNode *temp, *nextLink;
nextLink = head;
while(nextLink != NULL)
{
temp = nextLink->next;
delete nextLink;
nextLink = temp;
}
}
bool SortedLinkedList::isEmpty()
{
return (head == NULL);
}
void SortedLinkedList::addItem(int itemToInsert)
{
sslNode* cur;
sslNode* prev;
sslNode* newNode = new sslNode();
newNode->item = itemToInsert;
newNode->next = NULL;
cur = head;
prev = NULL;
bool moreToSearch (cur != NULL);
while (moreToSearch) //Find insertion point
{
if (cur->item > newNode->item) // while current location has a greater value then what needs to be inserted move pointers forward.
{
prev = cur;
cur = cur->next;
moreToSearch = (cur != NULL);
}
else // if current loacation and what is to be inserted are equal or less then we have found the point of insertion
{
moreToSearch = false;
}
}
if (prev = NULL)
{
newNode->next = head->next;
head = newNode;
}
else
{
prev->next = newNode;
newNode->next = cur;
}
//Insert as only item in list
//Insert in found location
}
int SortedLinkedList::popFirst()
{
sslNode* first;
first = head->next;
head = head->next;
int item = first->item;
return item;
}
Your problem is you forgot an =
if (prev = NULL)
{
newNode->next = head->next;
head = newNode;
}
else
{
prev->next = newNode;
newNode->next = cur;
}
if(prev = NULL)
should be
if(prev == NULL)
right now this is always false because prev becomes null which evaluates to false
and then it fails at
prev->next = newNode;
because your are dereferencing the null pointer.
You'll also want to treat the case where head == NULL before trying to insert anything. Basically if head == NULL, head = newNode;
It crashes because head is initialized to NULL. You probably want to make a dummy head node, depending on your design, or check if its NULL before using it in addItem().
This is how things go down:
SortedLinkedLis
t::SortedLinkedList() // ctor is called
...
head = NULL
SortedLinkedList::addItem(int)
sslNode* cur;
...
cur = head;
...
bool moreToSearch (cur != NULL) // this is surely false
...
if (prev = NULL)
{
newNode->next = head->next;
...//BUT head == NULL ! crash!