这是一项家庭作业,我已经编写了大部分代码,唯一无法弄清楚的是我必须有一个递归函数来排序链接列表按升序排列,递归函数按降序排列链接列表。我很迷茫。链接列表的递归递增和递归降序功能
这是我的整个代码。
using namespace std;
struct ListNode;
typedef ListNode* ListPtr;
struct ListNode
{
int number;
ListPtr next;
ListNode(int value, ListPtr ptr = NULL)
{
number = value;
next = ptr;
}
};
char Menu();
void Add(ListPtr &, int);
void Delete(ListPtr &, int);
void Ascend(ListPtr &);
void Descend(ListPtr &);
void Print(ListPtr &);
void DeleteList(ListPtr &);
int main()
{
ListPtr head = NULL;
char answer;
int input;
answer = Menu();
while(answer != 'Q')
{
if(answer == 'A')
{
cout << "Please enter in an integer: ";
cin >> input;
Add(head, input);
}
else if(answer == 'D')
{
cin >> input;
Delete(head, input);
}
else if(answer == 'P')
{
Ascend(head);
}
else if(answer == 'O')
{
Descend(head);
}
else if(answer == 'N')
{
Print(head);
}
else
{
cout << "Incorrect input, please try again.\n";
}
answer = Menu();
}
DeleteList(head);
return 0;
}
char Menu()
{
char uinput;
cout << "Please enter in one of the following:\n";
cout << "A: Add an item to the end of the list.\n";
cout << "D: Delete an item from the list.\n";
cout << "P: Print the list in ascending order.\n";
cout << "O: Print the list in descending order.\n";
cout << "N: Display the number of items in the list.\n";
cout << "Q: Quit.\n";
return toupper(uinput);
}
void Add(ListPtr &start, int item)
{
if(start->number > item || start == NULL)
start = new ListNode(item, start);
else
Add(start->next, item);
}
void Delete(ListPtr &start, int item)
{
if(start != NULL)
{
if(start->number == item)
ListPtr cur = start;
start = start->next;
delete cur;
}
else
{
Delete(start->next, item);
}
}
void Ascend(ListPtr &start)
{
}
void Descend(ListPtr &start)
{
}
void Print(ListPtr &start)
{
ListPtr cur = start;
int count = 0;
if(cur == NULL)
{
cout << "The list is empty.\n";
}
else
{
if(cur != NULL)
{
if(count % 10 == 0)
cout << endl;
cout << setw(5) << cur->number;
cur = cur->next;
count++;
}
}
cout << endl;
}
void DeleteList(ListPtr &start)
{
if(start != NULL)
{
DeleteList(start->next);
cout << "Deleting item " << start->number << endl;
delete start;
}
}
欢迎来到SO!特别是有这么多的代码,格式化它一贯将帮助人们阅读它来帮助你。此外,一定要解释什么是不工作,你试过什么等。 – J0e3gan
你的问题到底是什么?函数的逻辑?您是否熟悉递归函数以及如何编写一个? –
Sup的家伙,抱歉,我很新,如何写出来,我在一个C++编程2类,编程1和2都是入门级。问题是我不知道如何编写这两个部分,升序函数应该将列表中的数字按升序打印出来,而降序函数按降序排列。我只允许使用一个循环(我的菜单功能),所以这两个函数必须递归。我们已经完成了一些递归任务,因此我在基本层面上理解了它们,但是我们只是开始链接列表,所以将它与递归结合起来会让人困惑。 – Sayynt