题目的意思是:Display all data except the last node’s data item in CLL and return the sum of data items displayed
题目中的CLL就是循环链表英文单词的缩写。
实现这个功能,只能用递归,不能用循环。
建立循环链表是用rear指针,所以在传入参数时,就是得传入rear指针来指向最后一个,但是这个做法是不断开循环链表变成单链表的,所以就得再传一个指针来指向第一个节点。
下面就展示代码:
#include "clist.h"
int list::Display()
{
return Display(rear,rear->next);
}
int list::Display(node * rear, node * head)
{
if(!rear || !head)
return 0;
if(head != rear)
{
cout<<head->data<<" ";
return head->data + Display(rear,head->next);
}
else
return 0;
}
如果在最后不return 0的话,那么最后输出的结果就会出现很随机的数字。所以,还是得在最后return 0来表示最后一个节点不展示,只是返回数字0
下面是结果的展示: