鱼C论坛

 找回密码
 立即注册
查看: 1611|回复: 1

c++,用using namespace std;

[复制链接]
发表于 2023-11-13 20:17:37 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
〈4〉动态链表的每个结点包括一个整数和一个后继指针。分别编写过程完成如下操作:
    (1) 从键盘输入数据建立链表,并按数据的输入顺序建立链表。
    (2) 依次打印其中各结点的数据。
(3)*按与链表结点相反的次序打印各结点的值。
(4) 逐个释放所有结点的存储单元。
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2023-11-13 20:17:52 | 显示全部楼层
  1. #include <iostream>
  2. using namespace std;

  3. struct Node {
  4.     int data;
  5.     Node* next;
  6. };

  7. void insertNode(Node*& head, int value) {
  8.     Node* newNode = new Node;
  9.     newNode->data = value;
  10.     newNode->next = nullptr;

  11.     if (head == nullptr) {
  12.         head = newNode;
  13.     } else {
  14.         Node* temp = head;
  15.         while (temp->next != nullptr) {
  16.             temp = temp->next;
  17.         }
  18.         temp->next = newNode;
  19.     }
  20. }

  21. void printList(Node* head) {
  22.     Node* temp = head;
  23.     while (temp != nullptr) {
  24.         cout << temp->data << " ";
  25.         temp = temp->next;
  26.     }
  27.     cout << endl;
  28. }

  29. void reversePrint(Node* head) {
  30.     if (head == nullptr) {
  31.         return;
  32.     }
  33.     reversePrint(head->next);
  34.     cout << head->data << " ";
  35. }

  36. void deleteList(Node*& head) {
  37.     Node* temp;
  38.     while (head != nullptr) {
  39.         temp = head;
  40.         head = head->next;
  41.         delete temp;
  42.     }
  43. }

  44. int main() {
  45.     Node* head = nullptr;
  46.     int value;
  47.     while (cin >> value) {
  48.         insertNode(head, value);
  49.     }

  50.     cout << "正序打印:";
  51.     printList(head);

  52.     cout << "逆序打印:";
  53.     reversePrint(head);
  54.     cout << endl;

  55.     deleteList(head);

  56.     return 0;
  57. }
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-22 09:33

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表