我差不多完成了一个程序,但是我需要按升序对链表进行排序,并且我已经尝试了几个小时但无法弄明白,但程序的其余部分仍然有效。假设生成6个随机数并将它们存储在链表中并每次输出它直到它达到6个数字然后它停止然后删除每个元素直到它们全部被删除。但是假设在输出数字时对数字进行排序。它将节点存储在push_sorted函数中,所以我认为这是排序函数将要进行的,但我再也无法弄清楚如何对链表进行排序。无论如何感谢任何帮助,这是我的整个计划...
#include <iostream>
#include <ctime>
#include <cstdlib>
#include "SortedLinkedList.h"
#include <algorithm>
#include <list>
#include <array>
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(int pos)
{
node *temp =head;
struct node *t = NULL;
if(head->next==NULL)
{
free(head);
head=NULL;
}
else
{
while(temp->next != NULL)
{
t=temp;
temp=temp->next;
}
free(t->next);
t->next=NULL;
}
}
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 pos = 4;
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 --;
/*if (count == 1)
{
break;
}*/
cout << "Removing from back..." << endl;
pop_back(pos);
print();
count --;
pos-= 2;
}
system("pause");
return 0;
}
答案 0 :(得分:0)
您应该按照建议使用std::list
。但假设您出于其他原因需要它,您可以修改函数以比较值并交换节点,如下所示:
void push_sorted(int value)
{
node *n = new node;
n->data = value;
n->next = NULL;
if (!head)
{
head = n;
}
else
{
node *cursor = head;
if (head->data > value)
{
node *temp = head;
head = n;
n->next = temp;
return;
}
while (cursor->next)
{
if (cursor->next->data > value)
{
node *temp = cursor->next;
cursor->next = n;
n->next = temp;
return;
}
cursor = cursor->next;
}
cursor->next = n;
}
}
或者只是使用
std::list<int> lst;
lst.push_back(data);
lst.sort();
您也可以考虑std::vector
大部分时间执行std::list
。