COMP2113
COMP2113_ENGG1340 Programming technologies and Computer programming II [Section 2BC] [2023]
Loading...
Searching...
No Matches
build_list_forward.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
11void print_list(Node * head)
12{
13 Node * current = head;
14 while (current != NULL)
15 {
16 // process the current node, e.g., print the content
17 cout << current->info << " -> ";
18 current = current->next;
19 }
20 cout << "NULL\n";
21}
22
23void tail_insert(Node * & head,
24 Node * & tail, int num)
25{
26 Node * p = new Node;
27 p->info = num;
28 p->next = NULL;
29
30 if (head == NULL) {
31 head = p;
32 tail = p;
33 }
34 else {
35 tail->next = p;
36 tail = p;
37 }
38}
39
40
41
42int main()
43{
44 Node * head = NULL, * tail = NULL;
45 int num = 0;
46
47 // build linked list backward
48 cout << "input integers (-999 to end): ";
49 cin >> num;
50 while ( num != -999 ) {
51 tail_insert(head, tail, num);
52 cin >> num;
53 }
54
55 // print the items in the linked list
56 print_list(head);
57
58 return 0;
59}
void tail_insert(Node *&head, Node *&tail, int num)
int main()
void print_list(Node *head)
Definition 3.cpp:6
int info
Definition ex4ex5.cpp:7
Node * next
Definition ex4ex5.cpp:8