6 개의 난수를 생성하고 링크 된 목록에 넣고 출력하는 프로그램을 작성 중입니다. 그런 다음 6 개의 숫자를 모두 얻으면 첫 번째 노드를 삭제하고 나머지 5 개를 출력 한 다음 마지막 노드를 삭제하고 노드 4가 남을 때까지 나머지 4 개를 앞뒤로 출력합니다. 어쨌든 나는 연결된 목록을 생성하고 노드를 저장하여 출력 할 수 있으며 매번 첫 번째 노드를 삭제할 수 있지만 마지막 노드를 삭제하는 방법을 알 수는 없습니다. 마지막 노드를 삭제하는 방법에 대한 도움을 주시면 매우 감사하겠습니다. 나는 당신이 당신의 MCVE (입력, 출력, 삽입 등)의 나머지 부분을 완료 한링크 된 목록의 끝에서 삭제
#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;
}
이 마지막 두 번째 - 마지막 노드를 찾을 목록을 반복하는 추가 기능을 필요로한다. 마지막을 찾으면 쉽게 삭제할 수 있으며 두 번째 마지막 노드의 'next'를 NULL로 설정합니다. 나는'nullptr'에 대해 모든'NULL's를 교환하는 것이 좋습니다. 'NULL'은 당신이 원하지 않거나 필요로하지 않는 흥미로운 2 차 특성을 가지고 있습니다. – user4581301
연결된 목록은 재귀 적 데이터 구조입니다. 재귀를 사용하여 pop_back()을 구현하는 것이 좋습니다. 그렇습니다. 루프도 작동 할 수 있습니다. 귀하의 MCU는 귀하가 시도한 것을 보여 주어야합니다. 빈 pop_back()은 시도하지 않은 것을 보여줍니다. –
정의되지 않은 동작 - 새 것과 섞이지 마십시오. –