关于单链表的知识点,小编就不在这里介绍了,这次主要是用递归的方式来完成这道题目,不用循环方式。对于刚接触的递归的同学们,看这篇文章还是没关系的,主要是理解逻辑就行了。
下面是展示list.h里的代码是什么样的:
//This is the list.h file
#include<iostream>
#include<cctype>
#include<cstring>
using namespace std;
struct node
{
int data;
node * next;
};
class list
{
public:
//These functions are already provided for you
list(); //Supplied
~list(); //Supplied
void build(); //Supplied
void display(); //Supplied
//Duplicate the first node and place it at the end of a linear linked list
int duplicate_first();
private:
//Duplicate the first node and place it at the end of a linear linked list
int duplicate_first(node * head, node *& tail, int num);
node * head;
node * tail;
};
因为建立单链表的时候,用到了tail指针,那么就得在运行这个程序的时候,就得需要将tail指针pass by reference。
下面是展示如何实现这两个函数:
//This is the list.cpp file
#include "list.h"
//Duplicate the first node and place it at the end of a linear linked list
int list::duplicate_first()
{
return duplicate_first(head,tail,head->data);
}
int list::duplicate_first(node * head, node *& tail, int num)
{
if(!head)
return 0;
if(!head->next)
{
node * temp = new node;
temp->data = num;
temp->next = NULL;
head->next = temp;
int Num = tail->data;
tail = temp;
return Num+num;
}
return duplicate_first(head->next,tail,num);
}
因为在wrapper function里面就已经将num的值传给recursive function的num这个参数,那么就可以直接用这个num参数了。在recursive function里就直接用递归的方式就做出这个功能了。
下面是展示结果的:
从这个结果中就可以看出,The resulting list 中的已经将第一个节点插入到最后一个节点的后面去,然后返回了最后两个节点的总和。