关于这道题目的意思是,在单链表中,如果最后一个节点的数字跟第一节点的数字不一样,那么就展示最后一个节点。 关于单链表的知识点,小编就不在这里介绍了。
现在就直接上代码吧,小编是用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;
}
下面是结果展示:
这个是第一个节点和最后一个节点相同的情况
这个是第一个节点和最后一个节点不同的情况
这个就是小编关于这道题目的解法,若有错误,就请指教吧!