Write a c++ program that
-calls a function that creates a linked list with n Nodes entered by the user
-then create another function that adds a node at the start of that linked list
-and a third function that reverses the linked list updated in the second function
#include <iostream>
using namespace std;
struct Node {
struct Node * next;
double data;
};
struxt Node * head = new Node();
void addFirst(double x) {
struct Node * tmp = new Node();
tmp.data = x;
tmp.next = head;
head = tmp;
}
void addEnd(double x) {
struct Node * tmp = new Node();
struxt Node * foo = new Node();
foo = head;
tmp->data = x;
if (foo==nullptr) {
tmp->next=nullptr;
head=tmp;
}
while (foo->next!=nullptr) {
foo=foo->next;
}
tmp->next=nullptr;
foo->next=tmp;
}
void reverse() {
struct Node * current = head;
struct Node * prev = nullptr, * next = nullptr;
while (current != nullptr) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
head = prev;
}
int main() {
int n;
cout << "Enter n:"; cin >> n;
for (int i=0; i<n; i++) {
double x; cin >> x;
addEnd(x);
}
cout << "Add first!";
double x;
cin >> x;
addFirst(x);
reverse();
return 0;
}
Comments
Leave a comment