鱼C论坛

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

c++,用using namespace std;

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

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

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

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

使用道具 举报

发表于 2023-11-13 20:17:52 | 显示全部楼层
#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;
}
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-9-29 08:07

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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