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