COMP2113
COMP2113_ENGG1340 Programming technologies and Computer programming II [Section 2BC] [2023]
Loading...
Searching...
No Matches
print_list_reverse.cpp
Go to the documentation of this file.
1#include <iostream>
2
3using namespace std;
4
5struct Node
6{
7 int info;
8 Node * next;
9};
10
12{
13 if (head == NULL)
14 cout << "NULL";
15 else {
16 print_list_reverse( head->next );
17 cout << " <- " << head->info;
18 }
19}
20
21void print_list(Node * head)
22{
23 Node * current = head;
24 while (current != NULL)
25 {
26 // process the current node, e.g., print the content
27 cout << current->info << " -> ";
28 current = current->next;
29 }
30 cout << "NULL\n";
31}
32
33void tail_insert(Node * & head,
34 Node * & tail, int num)
35{
36 Node * p = new Node;
37 p->info = num;
38 p->next = NULL;
39
40 if (head == NULL) {
41 head = p;
42 tail = p;
43 }
44 else {
45 tail->next = p;
46 tail = p;
47 }
48}
49
50
51
52int main()
53{
54 Node * head = NULL, * tail = NULL;
55 int num = 0;
56
57 // build linked list backward
58 cout << "input integers (-999 to end): ";
59 cin >> num;
60 while ( num != -999 ) {
61 tail_insert(head, tail, num);
62 cin >> num;
63 }
64
65 // print the items in the linked list
66 cout << "print list in order: " << endl;
67 print_list(head);
68
69 // print the items in the linked list in reverse
70 cout << "print list in reverse: " << endl;
72
73 return 0;
74}
void tail_insert(Node *&head, Node *&tail, int num)
void print_list_reverse(Node *head)
int main()
void print_list(Node *head)
Definition 3.cpp:6
int info
Definition ex4ex5.cpp:7
Node * next
Definition ex4ex5.cpp:8