Question

Your task is to complete the following function/functions: 1. Given a position in the linked list,...

Your task is to complete the following function/functions: 1. Given a position in the linked list, delete the node at that position.(Silver problem - Mandatory ) 2. Print the sum of all negative elements in the linked list.(Gold problem) If you want, you can refer to the the previous recitation manual (which was on Linked Lists) to implement node deletion.

#include <iostream>

using namespace std;

//----------- Define Node ---------------------------------------------------
struct Node{
int key;
Node *next;
};

//----------- Define Linked List ---------------------------------------------------
class LinkedList
{
private:
Node *head;

public:
LinkedList(){
   head = NULL;
}
void insert_begin(int newKey);
void insert_end(int newKey);
int negativeSum();
bool deleteAtIndex(int index);
   bool deleteAtHead();
void printList();
};

void LinkedList::insert_begin(int newKey){
//1. ALLOCATE NODE
Node* newNode = new Node;

//2. PUT IN THE DATA
newNode->key = newKey;

//3. Make next of newNode as head
newNode->next = head;

//4. Change the head to newNode
head = newNode;
}

void LinkedList::insert_end(int newKey){
//1. ALLOCATE NODE
Node* newNode = new Node;

//2. PUT IN THE DATA
newNode->key = newKey;

//3. Make next of newNode as NULL
newNode->next = NULL;

//4. Check if head is not Null
if(head == NULL){
head = newNode;
return;
}

//4. Traverse the LinkedList till end
Node* temp = head;

while(temp->next != NULL){
temp = temp->next;
}
temp->next = newNode;
return;
}

//TODO
int LinkedList::negativeSum(){
if(head == NULL)
return 0;

int total = 0;
int count = 0;

// TODO Complete this function

cout<<"There is(are) "<<count<<" negative number(s) in the List"<<endl;
return total;

}

// Use deleteAtHead to delete the first item in the list
bool LinkedList::deleteAtHead()
{
   bool isDeleted = false;

if(head == NULL){
cout<< "List is already empty"<<endl;
return isDeleted;
}

Node *temp = head;
   head = temp->next;
   delete temp;
isDeleted = true;

   return isDeleted;
}

//TODO
bool LinkedList::deleteAtIndex(int n)
{
bool isDeleted = false;

if(head == NULL){
cout<< "List is already empty"<<endl;
return isDeleted;
}

   Node *pres = head;
   Node *prev = NULL;

//TODO Complete this function
//isDeleted = true;

   return isDeleted;
}

void LinkedList::printList(){
Node* temp = head;

while(temp->next != NULL){
cout<< temp->key <<" -> ";
temp = temp->next;
}

cout<<temp->key<<endl;
}

int main()
{
   LinkedList li;
   cout<<"Adding nodes to List:"<<endl;
   // 2
   li.insert_begin(2);
   li.printList();
   // -1->2
   li.insert_begin(-1);
   li.printList();
   // -1->2->-7
   li.insert_end(-7);
   li.printList();
// -1->2->-7->10
   li.insert_end(10);
   li.printList();
   // -1->2->-7->10->3
   li.insert_end(3);
   li.printList();
   cout<<endl;

   cout<<"Running delete function."<<endl;

   /*******************************
   Silver Problem - Implement the deleteAtIndex function
   ********************************/

   cout<<"Deleting node at index:"<<endl;
   if(!li.deleteAtIndex(3))
   {
       cout<<"Delete failed!"<<endl;
   }
   li.printList();
   cout<<endl;

if(!li.deleteAtHead())
   {
       cout<<"Delete failed!"<<endl;
   }
   li.printList();
   cout<<endl;


cout<<"Get the sum of negatives"<<endl;

   /*******************************
   Gold Problem - Implement the negativeSum function
   ********************************/
int negsum;
negsum = li.negativeSum();
cout<<"Sum of all the negative elements is "<<negsum<<endl;

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

#include <iostream>

using namespace std;

//----------- Define Node ---------------------------------------------------

struct Node{

int key;

Node *next;

};

//----------- Define Linked List ---------------------------------------------------

class LinkedList

{

private:

Node *head;

public:

LinkedList(){

head = NULL;

}

void insert_begin(int newKey);

void insert_end(int newKey);

int negativeSum();

bool deleteAtIndex(int index);

bool deleteAtHead();

void printList();

};

void LinkedList::insert_begin(int newKey){

//1. ALLOCATE NODE

Node* newNode = new Node;

//2. PUT IN THE DATA

newNode->key = newKey;

//3. Make next of newNode as head

newNode->next = head;

//4. Change the head to newNode

head = newNode;

}

void LinkedList::insert_end(int newKey){

//1. ALLOCATE NODE

Node* newNode = new Node;

//2. PUT IN THE DATA

newNode->key = newKey;

//3. Make next of newNode as NULL

newNode->next = NULL;

//4. Check if head is not Null

if(head == NULL){

head = newNode;

return;

}

//4. Traverse the LinkedList till end

Node* temp = head;

while(temp->next != NULL){

temp = temp->next;

}

temp->next = newNode;

return;

}

//TODO

int LinkedList::negativeSum(){

if(head == NULL)

return 0;

int total = 0;

int count = 0;

// TODO Complete this function

Node *pres = head;

while(pres != NULL){

if(pres->key < 0 ){

total = total + pres->key;

count = count + 1;

}

pres = pres->next;

}

cout<<"There is(are) "<<count<<" negative number(s) in the List"<<endl;

return total;

}

// Use deleteAtHead to delete the first item in the list

bool LinkedList::deleteAtHead()

{

bool isDeleted = false;

if(head == NULL){

cout<< "List is already empty"<<endl;

return isDeleted;

}

Node *temp = head;

head = temp->next;

delete temp;

isDeleted = true;

return isDeleted;

}

//TODO

bool LinkedList::deleteAtIndex(int n)

{

bool isDeleted = false;

if(head == NULL){

cout<< "List is already empty"<<endl;

return isDeleted;

}

Node *pres = head;

Node *prev = NULL;

//TODO Complete this function

//isDeleted = true;

// If head needs to be removed

if (n == 0)

{

return deleteAtHead();

}

for (int i=0; pres!=NULL && i<n-1; i++)

pres = pres->next;

if (pres == NULL || pres->next == NULL)

return false;

Node *next = pres->next->next;

free(pres->next); // Free memory

pres->next = next;

isDeleted = true;

return isDeleted;

}

void LinkedList::printList(){

Node* temp = head;

while(temp->next != NULL){

cout<< temp->key <<" -> ";

temp = temp->next;

}

cout<<temp->key<<endl;

}

int main()

{

LinkedList li;

cout<<"Adding nodes to List:"<<endl;

// 2

li.insert_begin(2);

li.printList();

// -1->2

li.insert_begin(-1);

li.printList();

// -1->2->-7

li.insert_end(-7);

li.printList();

// -1->2->-7->10

li.insert_end(10);

li.printList();

// -1->2->-7->10->3

li.insert_end(3);

li.printList();

cout<<endl;

cout<<"Running delete function."<<endl;

/*******************************

Silver Problem - Implement the deleteAtIndex function

********************************/

cout<<"Deleting node at index:"<<endl;

if(!li.deleteAtIndex(3))

{

cout<<"Delete failed!"<<endl;

}

li.printList();

cout<<endl;

if(!li.deleteAtHead())

{

cout<<"Delete failed!"<<endl;

}

li.printList();

cout<<endl;


cout<<"Get the sum of negatives"<<endl;

/*******************************

Gold Problem - Implement the negativeSum function

********************************/

int negsum;

negsum = li.negativeSum();

cout<<"Sum of all the negative elements is "<<negsum<<endl;

}





================================
See Output


Thanks, PLEASE UPVOTE if helpful

Add a comment
Know the answer?
Add Answer to:
Your task is to complete the following function/functions: 1. Given a position in the linked list,...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Q) Modify the class Linked List below to make it a Doubly Linked List. Name your...

    Q) Modify the class Linked List below to make it a Doubly Linked List. Name your class DoublyLinkedList. Add a method addEnd to add an integer at the end of the list and a method displayInReverse to print the list backwards. void addEnd(int x): create this method to add x to the end of the list. void displayInReverse(): create this method to display the list elements from the last item to the first one. Create a main() function to test...

  • #include <iostream> using namespace std; struct ListNode { float value; ListNode *next; }; ...

    #include <iostream> using namespace std; struct ListNode { float value; ListNode *next; }; ListNode *head; class LinkedList { public: int insertNode(float num); void deleteNode(float num); void destroyList(); void displayList(); LinkedList(void) {head = NULL;} ~LinkedList(void) {destroyList();} }; int LinkedList::insertNode(float num) { struct ListNode *newNode, *nodePtr = head, *prevNodePtr = NULL; newNode = new ListNode; if(newNode == NULL) { cout << "Error allocating memory for new list member!\n"; return 1; } newNode->value = num; newNode->next = NULL; if(head==NULL) { cout << "List...

  • Please rewrite this function using recursive function #include using namespace std; struct Node { char ch;...

    Please rewrite this function using recursive function #include using namespace std; struct Node { char ch; Node* next; }; class LinkedList { Node* head; public: LinkedList(); ~LinkedList(); void add(char ch); bool find(char ch); bool del(char ch); friend std::ostream& operator<<(std::ostream& out, LinkedList& list); }; LinkedList::LinkedList() { head = NULL; } LinkedList::~LinkedList() { Node* cur = head, * tmp; while (cur != NULL) { tmp = cur->next; delete cur; cur = tmp; } } void LinkedList::add(char ch) { Node* cur = head,...

  • **HELP** Write a function that takes a linked list of items and deletes all repetitions from the ...

    **HELP** Write a function that takes a linked list of items and deletes all repetitions from the list. In your implementation, assume that items can be compared for equality using ==, that you used in the lab. The prototype may look like: void delete_repetitions(LinkedList& list); ** Node.h ** #ifndef Node_h #define Node_h class Node { public: // TYPEDEF typedef double value_type; // CONSTRUCTOR Node(const value_type& init_data = value_type( ), Node* init_link = NULL) { data_field = init_data; link_field = init_link;...

  • In C++, for the provided template linked list class create a derived class of it which...

    In C++, for the provided template linked list class create a derived class of it which adds the functionality to it to find the high and low value of any given data stored in the list. The derived class must be a template. LinkedList.h #pragma once #include <iostream> using namespace std; template <class T> class ListNode {    public:        T data;        ListNode<T>* next;        ListNode(T data)        {            this->data = data;...

  • C++ - I have a doubly linked list, but I haven't been able to get the...

    C++ - I have a doubly linked list, but I haven't been able to get the "reverse list" option in the code to work(It's option #in the menu in the program). I received this guidance for testing: Test 4 cases by entering (in this order) c,a,z,k,l,m This tests empty list, head of list, end of list and middle of list. Then delete (in this order) a,z,l. This tests beginning, end and middle deletes. This exhaustively tests for pointer errors. #include...

  • Follow the TODOs and complete the insertItem(), searchItem() and printTable() functions in hash.cpp. The hash function...

    Follow the TODOs and complete the insertItem(), searchItem() and printTable() functions in hash.cpp. The hash function has already been implemented for you. // hash.CPP program to implement hashing with chaining #include<iostream> #include "hash.hpp" using namespace std; node* HashTable::createNode(int key, node* next) { node* nw = new node; nw->key = key; nw->next = next; return nw; } HashTable::HashTable(int bsize) { this->tableSize= bsize; table = new node*[tableSize]; for(int i=0;i<bsize;i++) table[i] = nullptr; } //function to calculate hash function unsigned int HashTable::hashFunction(int key)...

  • Please fill in this code to reverse a linked list: (written in C/C++) #include #include #include...

    Please fill in this code to reverse a linked list: (written in C/C++) #include #include #include using namespace std; /* Link list node */ struct Node { int data; // your code here }; /* Function to reverse the linked list */ static void reverse(struct Node** head_ref) { // your code here } /* Function to push a node */ void push(struct Node** head_ref, int new_data) { // your code here } /* Function to print linked list */ void...

  • CSCI 2010 Lab11 Link-Lists Lab 11A Linked-Lists Preparation Create a Visual Studio C++ Project C...

    CSCI 2010 Lab11 Link-Lists Lab 11A Linked-Lists Preparation Create a Visual Studio C++ Project C2010Lab11A Add the following to the project. //LinkedList.cpp #include <cstdlib> #include "LinkedList.h" using namespace std; //--------------------------------------------------- //List Element Members //--------------------------------------------------- ListElement::ListElement(int d, ListElement * n) {    datum=d;    next=n; } int ListElement::getDatum () const {    return datum; } ListElement const* ListElement::getNext () const {    return next; } //--------------------------------------------------- //LinkedList Members //--------------------------------------------------- LinkedList::LinkedList () {    head=NULL; } void LinkedList::insertItem(int item) {    ListElement *currPtr = head;    ListElement *prevPtr =...

  • BELOW IS THE CODE I ALREADY HAVE Linked List - Delete Modify Lab 5 and include...

    BELOW IS THE CODE I ALREADY HAVE Linked List - Delete Modify Lab 5 and include the method to delete a node from the Linked List. In summary: 1) Add the method Delete 2) Method call to delete, with a number that IS in the list 3) Method call to delete, with a number that is NOT in the list - Be sure to include comments - Use meaningful identifier names (constants where appropriate) import java.io.*; 1/ Java program to...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT