题目的意思就是,在单链表里,如何用递归来将最后一个节点删除掉。
下面是代码展示:
//This is the list.h file
#include<iostream>
#include<cstring>
#include<cctype>
using namespace std;
struct node
{
int data;
node * next;
};
class list
{
public:
//These functions are already written for you
list(); //supplied
~list(); //supplied
void build(); //supplied
void dispaly(); //supplied
//Remove the end of the LLL
//Return the last node to the main function
int remove_end();
private:
//Remove the end of the LLL
//Return the last node to the main function
int remove_end(node *& head, node *& tail);
node * head;
node * tail;
};
因为,建立的链表用到tail指针,所以在删除最后一个节点的时候,那么就得将pass by reference of the tail pointer and the head pointer。
下面展示,如何来实现这两个函数的代码:
#include "list.h"
int list::remove_end()
{
return remove_end(head,tail);
}
int list::remove_end(node *& head, node *& tail)
{
if(!head)
{
int num = head->data;
delete head;
head = NULL;
return num;
}
if(!head->next->next)
{
int num = head->next->data;
delete head->next;
head->next = NULL;
tail = head;
return num;
}
return remove_end(head->next,tail);
}
小编在这里就不写如何在主函数里调用来运行了
下面就展示结果:
从结果中可以看出,已经将原先的list的最后一个节点(也就是数字’2’)删除,那么返回的就是之前最后一个节点。