【发布时间】:2020-11-10 07:45:25
【问题描述】:
尝试使用链表实现冒泡排序,但它不起作用。任何人都可以识别我的代码中的问题。我认为在singlylinkedist 类中有一个名为bubblesort 的函数,其中for 循环不起作用,用于对链表进行完全排序。它只对列表进行一次排序,但不会将其排序到链表的大小。
#include<iostream>
using namespace std;
class Node{
public:
int data;
Node *next;
Node()
{
data = 0;
next = NULL;
}
Node(int d)
{
data = d;
}
};
class singlylinkedlist{
public:
Node *head,*tail;
singlylinkedlist()
{
head = NULL;
tail = NULL;
}
void appendNode(Node *temp)
{
if (head == NULL)
{
head = temp;
tail = temp;
cout << "Node Appended" << endl;
}
else
{
tail->next = temp;
tail = tail->next;
cout << "Node Appended" << endl;
}
}
void prependNode(Node *temp)
{
temp->next = head;
head = temp;
cout<< "Node Prepended" << endl;
}
int getdata(int pos)
{
Node *curr = new Node;
curr = head;
for(int i=1;i<pos;i++)
{
curr = curr->next;
}
return curr->data;
}
void printList()
{
if (head == NULL)
{
cout << "No Nodes in Singly Linked List";
}
else
{
cout << endl << "Singly Linked List Values : ";
Node *temp = head;
while (temp != NULL)
{
cout << "--> "<<temp -> data;
temp = temp -> next;
}
cout<<"\n";
}
}
int ListSize()
{
int count=0;
if (head == NULL)
{
cout << "No Nodes in Singly Linked List";
}
else
{
Node *temp = head;
while (temp != NULL)
{
temp = temp -> next;
count = count+1;
}
}
return count;
}
void bubblesort(Node *temp)
{
temp= head;
Node *ptr;
Node *prev = NULL;
for(int j=0;j<ListSize();j++)
{
while(temp!=NULL && temp->next!=NULL){
if(temp->data > temp->next->data){
if(prev == NULL){
ptr = temp->next;
temp->next = ptr->next;
ptr->next = temp;
head = prev = ptr;
}
else{
ptr = temp->next;
prev->next = ptr;
temp->next = ptr->next;
ptr->next = temp;
prev = ptr;
}
}
else{
ptr = temp->next;
prev = temp;
temp = ptr;
}
}
}
}
};
int main()
{
singlylinkedlist s;
int option;
int data1;
int pos;
do{
cout << "\nWhat operation do you want to perform? Select Option number. Enter 0 to exit." << endl;
cout << "1. appendNode()" << endl;
cout << "2. prependNode()" << endl;
cout << "3. getdata()" << endl;
cout << "6. printList()" << endl;
cout << "7. bubblesort()" << endl;
cin>>option;
Node *temp = new Node;
switch (option) {
case 0:
break;
case 1:
cout << "Append Node Operation \nEnter data of the Node to be Appended" << endl;
cin >> data1;
temp->data = data1;
temp->next = NULL;
s.appendNode(temp);
break;
case 2:
cout<<"Prepend Node Operation \nEnter data of the Node to be Prepended" << endl;
cin>>data1;
temp->data = data1;
temp->next = NULL;
s.prependNode(temp);
break;
case 3:
cout<<"enter position to get data"<<endl;
cin>>pos;
cout<<"DATA AT GIVEN INDEX IS " << s.getdata(pos);
break;
case 6:
s.printList();
break;
case 7:
s.bubblesort(temp);
s.printList();
break;
}
}while (option != 0);
}
【问题讨论】:
-
仅供参考,C++ 不是 Java。您在
getdata中所做的分配完全没有意义,并且会在两行短的时间内泄漏内存。只是说。 -
兄弟感谢您告诉我。我很感激。但是你能帮我解决我的问题吗??
-
你熟悉冒泡排序吗? IE。您是否设法在数组中为自己编程了一个冒泡的
ints? -
你熟悉链表吗? IE。您是否设法用插入(中间/开始/结束)、删除(中间/开始/结束)和打印为自己编写了一个链表?
-
@Yunnosch 是的,我很熟悉它。我首先使用数组实现了它,然后我使用喜欢的列表来实现它,我必须通过交换节点对其进行排序。请帮助我并解决我的问题
标签: c++ data-structures bubble-sort