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()似乎表明你還沒有嘗試過? –
未定義的行爲 - 永遠不要與新的自由混合。 –