C++ Program Using the basic Linked List program, (1) Create a linked list from f
ID: 3571579 • Letter: C
Question
C++ Program
Using the basic Linked List program,
(1) Create a linked list from file input data
(2) Print the linked list, with 10 values per line
Add new functions:
(1) A function gets user input of a value to look for in the list, and reports how many times it
appears (could be 0)
(2) A function counts the nodes in a list and reports how many there are.
(3) A function gets user input of a value to delete, and deletes the first node found which has
that value. (Does it matter whether that node is first, last, or in the middle of the list?)
The main program calls the functions and shows that they work.
Explanation / Answer
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
// declaring node
struct node
{
int info;
struct node *next;
}*start;
class LinkedListTest
{
public:
node* createLinkedListNode(int);
void insertNode();
void deleteNode();
void print();
LinkedListTest()
{
start = NULL;
}
};
main()
{
int userChoice;
LinkedListTest list1;
start = NULL;
while (1)
{
cout<<endl<<"**************** Linked List **************"<<endl;
cout<<"1.Insert"<<endl;
cout<<"2.Delete"<<endl;
cout<<"3.Print"<<endl;
cout<<"4.Exit "<<endl;
cout<<"Enter your userChoice : ";
cin>>userChoice;
switch(userChoice)
{
case 1:
cout<<"Inserting..: "<<endl;
list1.insertNode();
break;
case 2:
cout<<"Deleting..: "<<endl;
list1.deleteNode();
break;
case 3:
cout<<"Printing linked list:"<<endl;
list1.print();
break;
case 10:
cout<<"Exit"<<endl;
exit(1);
break;
default:
cout<<"Enter correct chocie..."<<endl;
}
}
}
// constructor
node *LinkedListTest::createLinkedListNode(int val)
{
struct node *tempNode;
tempNode = new(struct node);
tempNode->info = val;
tempNode->next = NULL;
return tempNode;
}
// insert element
void LinkedListTest::insertNode()
{
int val;
cout<<"Enter value to insert: ";
cin>>val;
struct node *tempNode, *temp;
tempNode = createLinkedListNode(val);
temp = start;
while (temp->next != NULL)
{
temp = temp->next;
}
tempNode->next = NULL;
temp->next = tempNode;
}
// delete element
void LinkedListTest::deleteNode()
{
int val, i;
if (start == NULL)
{
cout<<"List is empty";
return;
}
cout<<"Enter value to be deleted: ";
cin>>val;
struct node *temp, *ptr;
temp = start;
while (temp != NULL)
{
if(temp->val == val){
temp = temp ->prev;
break;
}
temp = temp->next;
}
}
// display data
void LinkedListTest::print()
{
struct node *tempNode;
if (start == NULL)
{
cout<<"Empty list";
return;
}
tempNode = start;
cout<<"Elements are: ";
while (tempNode != NULL)
{
cout<<tempNode->info<<"->";
tempNode = tempNode->next;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.