0
我正在编写一个程序,它会生成6个随机数并将它们放入链表中并输出它们。然后在得到全部6个数字后,删除第一个节点并输出剩余的5个数据,然后它将删除最后一个节点,并输出剩余的4个数字并来回输出,直到没有剩余节点。无论如何,我能够创建链表和存储节点,并输出它们,我可以删除第一个节点,但我不知道如何删除最后一个节点。任何帮助如何删除最后一个节点将不胜感激。我使用该函数pop_back删除最后一个节点...从链表的末尾删除
#include <iostream>
#include <ctime>
#include <cstdlib>
#include "SortedLinkedList.h"
using namespace std;
struct node
{
int data;
node *next;
};
node *head = NULL;
void push_sorted(int value)
{
node *newNode = new node;
newNode->data = value;
newNode->next = NULL;
if(head == NULL)
{
head = newNode;
}
else
{
node *newNode_2 = head;
while(newNode_2->next != NULL)
{
newNode_2 = newNode_2-> next;
}
newNode_2->next = newNode;
}
}
void pop_front()
{
node *temp;
temp = head;
head = head->next;
free(temp);
}
void pop_back()
{
}
bool isEmpty(int count)
{
if(count == 0)
{
return false;
}
else
{
return true;
}
}
void print()
{
node* current = head;
while(current != NULL)
{
cout << current-> data << " ";
current = current->next;
}
cout << endl;
}
int main()
{
int count = 6;
const int NUMS = 6; //insert elements into the sorted linked list in an ascending order
const int RANGE = 21; //each element is in the range [-10, 10]
/*SortedLinkedList mylist;*/
srand(time(0));
for (int i = 0; i < NUMS; i++)
{
int data = (rand() % RANGE) - 10;
cout << "Adding " << data << " to the sorted linked list: " << endl;
push_sorted(data);
print();
}
while ((isEmpty(count) == true))
{
cout << "Removing from front..." << endl;
pop_front();
print();
count --;
cout << "Removing from back..." << endl;
pop_back();
print();
count --;
}
system("pause");
return 0;
}
这需要一个额外的功能列表以迭代找到最后和倒数第二个节点。一旦找到最后一个,删除它很容易,然后将倒数第二个节点的下一个节点设置为NULL。尽管如此,我建议将所有'NULL'交换为'nullptr'。 'NULL'有一些你不想或不需要的有趣的次要特征。 – user4581301
你的链表是一个递归数据结构。我建议你尝试递归来实现pop_back()。 (叹气)是的,一个循环也可以工作。你的mcve应该显示你的尝试。一个空的pop_back()似乎表明你还没有尝试过? –
未定义的行为 - 永远不要与新的自由混合。 –