c ++ 链表的头插和尾插(有哨兵节点)附着菜单思路

废话不多说,直接码,设置函数比较多,比较绕,因为后面还想增加数据结构的一些功能

#include <iostream>
using namespace std;

struct node
{
    int data;
    node* nextnode;
};

node* headinsert(node* head)
{
    int i;
    for (i = 0; i < 3; i++)
    {
        node* point = new node;
        point->data = i;
        point->nextnode = head;
        head = point;
    }
    node* ptr = head;
    while (ptr != nullptr)
    {
        cout << ptr->data << endl;
        ptr = ptr->nextnode;
    }
    system("pause");
    return head;
}

node* tailinsert(node* head)
{
    node* tail = head;
    int i;
    for (i = 0; i < 3; i++)
    {
        node* point = new node;
        point->data = i;
        point->nextnode = nullptr;
        tail->nextnode = point;
        tail = point;
    }
    node* ptr = head->nextnode;
    while (ptr != nullptr)
    {
        cout << ptr->data << endl;
        ptr = ptr->nextnode;
    }
    system("pause");
    return head;
}

void deleted(node*& head)
{
    node* ptr = head;
    while (ptr != nullptr)
    {
        node* next = ptr->nextnode;
        delete ptr;
        ptr = next;
    }
    head = nullptr;
    cout << "success for delete" << endl;
    system("pause");
}

void creatlist()
{
    node* head = nullptr;
flag:
    cout << "please put your option" << endl;
    cout << "'1' use headinsert" << endl;
    cout << "'2' use tailinsert" << endl;
    cout << "'3' delete list" << endl;
    cout << "'4' end" << endl;
    int a;
    cin >> a;
    switch (a)
    {
    case 1:
    {
        if (head != nullptr) // 如果链表还存在,删除它
        {
            deleted(head);
        }
        head = headinsert(head); // 使用已经创建的head变量
        system("cls");
        goto flag;
    }
    break;
    case 2:
    {
        if (head != nullptr) // 如果链表还存在,删除它
        {
            deleted(head);
        }
        head = new node;
        head->nextnode = nullptr;
        head = tailinsert(head); // 使用已经创建的head变量
        system("cls");
        goto flag;
    }
    break;
    case 3:
    {
        deleted(head);
        system("cls");
        goto flag;
    }
    break;
    case 4:
    {
        if (head != nullptr) // 如果链表还存在,删除它
        {
            deleted(head);
        }
        return;
    }
    break;
    }
}

int main()
{
    creatlist();
    return 0;
}
 

  • 13
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值