USING C++ Using linked lists, write a program that does the following: 1-) Allow
ID: 3558082 • Letter: U
Question
USING C++ Using linked lists, write a program that does the following: 1-) Allow user to enter a list of numbers (stop reading numbers when user enters -1) 2-) Create a linked list that will hold the entered numbers 3-) Allow the user to display the list 4-) Allow the user to delete any element from the list To test your code, I will enter several numbers, then display the contents of the list, after which, I will delete one value, it could be any value, the first, middle, or last, then display the list again.
CREDIT WILL NOT BE GIVEN IF YOU DO NOT ACTUALLY READ THE ASSIGNMENT! I WILL NOT PAY YOU TO HELP ME WITH THIS.
Explanation / Answer
#include <iostream>
using namespace std;
struct node
{
int value;
node* next;
};
class LList
{
public:
LList();
~LList();
void add(int v);
bool remove(int v);
void display();
private:
node* head;
node* tail;
};
LList::LList()
{
head = tail = 0;
}
LList::~LList()
{
while (head != NULL)
{
node* p = head;
head = head->next;
delete p;
}
}
void LList::add(int v)
{
node* p = new node();
p->value = v;
p->next = NULL;
if (tail != NULL)
tail->next = p;
else
head = p;
tail = p;
}
bool LList::remove(int v)
{
node* prev = NULL;
node* p = head;
while (p != NULL && p->value != v)
{
prev = p;
p = p->next;
}
// no such element
if (p == NULL)
return false;
// p is head
if (prev == NULL)
head = p->next;
else
prev->next = p->next;
if (p == tail)
tail = prev;
delete p;
return true;
}
void LList::display()
{
node* p = head;
while (p != NULL)
{
cout << p->value << " ";
p = p->next;
}
cout << endl;
}
int main()
{
cout << "Enter numbers(-1 end): ";
int num;
LList myList;
cin >> num;
while (num != -1)
{
myList.add(num);
cin >> num;
}
cout << "Numbers in list: ";
myList.display();
cout << "Enter a number to delete: ";
cin >> num;
if (myList.remove(num))
cout << num << " deleted." << endl;
else
cout << "No such element." << endl;
cout << "Numbers in list: ";
myList.display();
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.