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
3
using namespace
std;
4
5
struct
Node
6
{
7
int
info
;
8
Node
*
next
;
9
};
10
11
void
print_list_reverse
(
Node
* head)
12
{
13
if
(head == NULL)
14
cout <<
"NULL"
;
15
else
{
16
print_list_reverse
( head->
next
);
17
cout <<
" <- "
<< head->
info
;
18
}
19
}
20
21
void
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
33
void
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
52
int
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;
71
print_list_reverse
(head);
72
73
return
0;
74
}
tail_insert
void tail_insert(Node *&head, Node *&tail, int num)
Definition
print_list_reverse.cpp:33
print_list_reverse
void print_list_reverse(Node *head)
Definition
print_list_reverse.cpp:11
main
int main()
Definition
print_list_reverse.cpp:52
print_list
void print_list(Node *head)
Definition
print_list_reverse.cpp:21
Node
Definition
3.cpp:6
Node::info
int info
Definition
ex4ex5.cpp:7
Node::next
Node * next
Definition
ex4ex5.cpp:8
Module8
Sample Code
Linked Lists
print_list_reverse.cpp
Generated on Sun Sep 29 2024 16:39:53 for COMP2113 by
1.12.0