在单链表中,如果最后一个节点跟第一个节点相同的话,就不展示最后一个节点,若不同就展示最后一个节点

关于这道题目的意思是,在单链表中,如果最后一个节点的数字跟第一节点的数字不一样,那么就展示最后一个节点。 关于单链表的知识点,小编就不在这里介绍了。

现在就直接上代码吧,小编是用C++来实现的。

//This is the list.h
#include<iostream>
#include<cstring>
#include<cctype>

using namespace std;

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

class list
{
    public:
        //These functions are already written 
        list();
        ~list();
        void build();
        void display();

        //Display just the last piect of data in a linear linked list, if it isn't the same as the first node
        int display_last();

    private:
        //Display just the last piect of data in a linear linked list, if it isn't the same as the first node
        int get_first(node * head);
        int get_last(node * tail);

        node * head;
        node * tail;
};

下面是实现这几个函数的代码展示:

//This is the list.cpp
#include "list.h"

int list::display_last()
{
    int first = get_first(head);
    int last = get_last(tail);
    if(first != last)
        return last;
    else
        return -1;
}

int list::get_first(node * head)
{
    if(!head)
        return 0;
    return head->data;
}

int list::get_last(node * tail)
{
    return tail->data;
}

下面是在主函数的代码展示

//This is the main function
#include "list.h"

int main()
{
    list object;
    object.build();  //Builds a LLL
    object.display(); //Displays the LLL

    int result = object.display_last();
    if(result >= 0)
        return result;
    else
        cout<<"The first node is the same as the last node."<<endl;

    return 0;
}

下面是结果展示:
这个是第一个节点和最后一个节点相同的情况
这个是第一个节点和最后一个节点相同的情况

这个是第一个节点和最后一个节点不同的情况
这里写图片描述

这个就是小编关于这道题目的解法,若有错误,就请指教吧!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值