欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

键盘输入创建链表:先进先出与先进后出

程序员文章站 2024-03-18 09:16:10
...

键盘输入创建链表:先进先出与先进后出

1.先进先出

#include<iostream>
#include<vector>
#include<stdio.h>
#include<stdlib.h>

using namespace std;

struct Linked_list
{
    int num;
    Linked_list *next;
};

int main()
{
    Linked_list *head = NULL;
    Linked_list *m = NULL;
    Linked_list *tail = NULL;
    char a;


    while(1)
    {
        Linked_list *p = new Linked_list;
        cout<<"请输入链表数:"<<endl;
        cin>>p->num;
        if(head == NULL)
        {
            head = p;
            tail = head;
            p->next = NULL;
        }
        else
        {
            tail->next = p;
            tail = tail->next;
        }
        cout<<"是否继续输入数字Y/N?"<<endl;
        cin>>a;
        if(a == 'N')
        {
            tail->next = NULL;
            break;
        }    
        else
        {
            continue;
        }
        

    }
   
    cout<<"输出链表中的各个数据:"<<endl;
    m = head;
    while(m != NULL)
    {
        cout<<m->num<<endl;
        m = m->next;
    }
    return 0;
}

要点:在先进先出的情况下,并能用p = p->next;来替代tail = tail->next。因为p总是新建的,它的作用于无法直接作用于头尾链表指针,我们需要的是设计好与头尾链表指针相关的程序。
2. 先进后出

#include<iostream>
#include<vector>
#include<stdio.h>
#include<stdlib.h>

using namespace std;

struct Linked_list
{
    int num;
    Linked_list *next;
};

int main()
{
    Linked_list *head = NULL;
    Linked_list *m = NULL;
    char a;
    

    while(1)
    {
        Linked_list *p = new Linked_list;
        cout<<"请输入链表数:"<<endl;
        cin>>p->num;
        if(head == NULL)
        {
            p->next = NULL;
            head = p;
        }
        else
        {
            p->next = head;
            head = p;
        }
        cout<<"是否继续输入数字Y/N?"<<endl;
        cin>>a;
        if(a == 'N')
            break;
        else
        {
            continue;
        }
        

    }
    cout<<"输出链表中的各个数据:"<<endl;
    m = head;
    while(m != NULL)
    {
        cout<<m->num<<endl;
        m = m->next;
    }
    return 0;
}