1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
|
#include<iostream>
using namespace std;
struct node_ll {
int payload;
node_ll *next; // pointer to the next node
};
void head_insert(node_ll **list, int pload);
void tail_insert(node_ll **list, int pload);
void print_ll(node_ll **list);
int main() {
node_ll *alist = NULL;
cout << "Empty list a to start\n";
head_insert(&alist, 2);
head_insert(&alist, 4);
head_insert(&alist, 6);
cout << "List a after head insertion of 2,4,6 is \n";
print_ll(&alist);
cout << '\n';
node_ll *blist = NULL;
cout << "Empty list b to start\n";
tail_insert(&blist, 2);
tail_insert(&blist, 4);
tail_insert(&blist, 6);
cout << "List b after tail insertion of 2,4,6 is \n";
print_ll(&blist);
cout << '\n';
};
void head_insert(node_ll **list, int pload) {
node_ll *temp = new node_ll;
temp->payload = pload;
temp->next = *list;
*list = temp;
};
void tail_insert(node_ll **list, int pload) {
node_ll *temp = new node_ll;
if (*list == NULL) head_insert(list,pload);
else {
//set temp to last node
for (temp = *list; temp->next; temp = temp->next);
temp->next = new node_ll;
temp->next->payload = pload;
temp->next->next = NULL;
};
};
void print_ll(node_ll **list) {
node_ll *temp;
temp = *list;
while (temp) {
cout << temp->payload << '\n';
temp = temp->next;
};
}
|