c++,用using namespace std;
〈4〉动态链表的每个结点包括一个整数和一个后继指针。分别编写过程完成如下操作:(1) 从键盘输入数据建立链表,并按数据的输入顺序建立链表。
(2) 依次打印其中各结点的数据。
(3)*按与链表结点相反的次序打印各结点的值。
(4) 逐个释放所有结点的存储单元。 #include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
void insertNode(Node*& head, int value) {
Node* newNode = new Node;
newNode->data = value;
newNode->next = nullptr;
if (head == nullptr) {
head = newNode;
} else {
Node* temp = head;
while (temp->next != nullptr) {
temp = temp->next;
}
temp->next = newNode;
}
}
void printList(Node* head) {
Node* temp = head;
while (temp != nullptr) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
void reversePrint(Node* head) {
if (head == nullptr) {
return;
}
reversePrint(head->next);
cout << head->data << " ";
}
void deleteList(Node*& head) {
Node* temp;
while (head != nullptr) {
temp = head;
head = head->next;
delete temp;
}
}
int main() {
Node* head = nullptr;
int value;
while (cin >> value) {
insertNode(head, value);
}
cout << "正序打印:";
printList(head);
cout << "逆序打印:";
reversePrint(head);
cout << endl;
deleteList(head);
return 0;
}
页:
[1]