Question
c++ I need to add the following two functions to the code I currently have and am unsure of how implement them. The current code
c++
I need to add the following two functions to the code I currently have and am unsure of how implement them. The current code manipulates linked lists.
void deleteNote(int x) The function deletes the node with the value x.
void reverseList() - The function reverses all nodes in the list.
Thank you ahead of time for your help!
Here is the code I have right now:
#include
using namespace std;
struct ListNode { int data; ListNode* next; ListNode(int x) { data = x; next = nullptr; } };
class LinkedList {
private: ListNode* head = nullptr; ListNode* tail = nullptr;
public: void addNode(int x) { ListNode *newNode = new ListNode(x);
if(head == nullptr) { head = newNode; tail = newNode; return; }
tail -> next = newNode; tail = tail -> next; }
void addNodeToSortedList(int x) { ListNode *newNode = new ListNode(x);
if(head == nullptr) { head = newNode; tail = newNode; return; }
if(x < head -> data) { newNode -> next = head; head = newNode; return; }
ListNode *temp = head; ListNode *prev = temp;
while(temp != nullptr) { if(x < temp -> data) { prev -> next = newNode; newNode -> next = temp; return; } prev = temp; temp = temp -> next; } tail -> next = newNode; tail = newNode; }
void deleteAll() { ListNode *temp = head; while(temp != nullptr) { ListNode *t = temp -> next; free(temp); temp = t; } head = nullptr; tail = nullptr; }
void display() { ListNode *t = head; while(t != nullptr) { cout << t -> data << " "; t = t -> next; } cout << endl; } };
int main() { LinkedList ll; ll.addNode(1); ll.addNode(2); ll.addNode(3); ll.addNode(4); ll.addNode(5); ll.addNode(6); ll.addNode(7); ll.addNode(8); /// Display 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> @ ll.display(); ll.deleteNode(8);
/// Display 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> @ ll.display();
ll.deleteNode(1);
/// Display 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> @ ll.display(); ll.deleteNode(5); /// Display 2 -> 3 -> 4 -> 6 -> 7 -> @ ll.display();
ll.reverseList();
/// Display 7 -> 6 -> 4 -> 3 -> 2 -> @ ll.display();
ll.deleteAll(); return 0; }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started