我想编写一个程序,它将创建一个链表并使用冒泡排序对该列表进行排序。我写过但是当我运行程序时它不起作用并且程序被压碎了。
linkedList.h
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
class linkedList
{
public:
linkedList();
virtual ~linkedList();
void add(int v);
void insert(int v , int pos);
void remove(int v );
linkedList bubbleSort();
void display();
protected:
private:
struct Node
{
int value;
Node *next;
};
Node * head;
int lenght;
};
#endif // LINKEDLIST_H
请检查“void add(int v)”和“linkedList bubbleSort()”。这两个功能不起作用。
linkedList.cpp
#include "linkedList.h"
#include <iostream>
using namespace std;
linkedList::linkedList()
{
//ctor
head = NULL;
lenght = 0;
}
linkedList::~linkedList()
{
//dtor
}
void linkedList::add(int v)
{
Node *nptr = new Node;
nptr->value = v;
if(head==NULL)
{
head= nptr;
nptr->next = NULL;
}
else
{
Node *location = head;
while(location->next != NULL)
{
location = location->next;
}
location->next = nptr;
}
lenght++;
}
void linkedList::insert(int v , int pos)
{
lenght++;
Node *nptr = new Node;
nptr->value = v;
if(pos==1 || head==NULL)
{
nptr->next = head;
head = nptr;
}
else
{
Node *location = head ;
for(int i =1;i<pos-1 && location->next != NULL ;i++ )
{
location = location->next;
}
nptr->next = location->next;
location->next = nptr;
}
}
void linkedList::remove(int v)
{
Node *location = head;
if(head==NULL)
{
cout<<"list empty , delete not possible .";
}
else
{
while(location->next->value != v)
{
location= location->next;
}
Node *temp = location->next;
location->next= location->next->next;
delete temp;
}
}
linkedList linkedList::bubbleSort()
{
int count;
linkedList nList ;
bool swaped = false;
nList.head = head;
if(head== NULL)
cout<<"List is empty";
else
{
Node *temp1;
Node *temp2;
temp1 = head;
temp2 = nList.head;
while(temp1 != NULL)/// copying whole list to the nlist ;
{
count++;
temp1 = temp1->next;
temp2 = temp2->next;
temp2 = temp1;
}
temp2->next = NULL;
temp2 = nList.head;///****
//for(int i=0;i<count-1;i++)
while(temp2!=NULL)
{
// swaped = false;
temp2 = nList.head;
//for(int j = 0;j<count-1-i;j++)
while(temp2->next!=NULL)
{
if(temp2->value > temp2->next->value)
{
int temp = temp2->value;
temp2->value = temp2->next->value;
temp2->next->value = temp;
//swaped = true;
}
temp2= temp2->next;
}
/*if(swaped==false)
break;*/
}
return nList;
}
}
void linkedList::display()
{
Node *loc = head;
while(loc != NULL)
{
cout<<loc->value<<" ";
loc = loc->next;
}
}
//Main function
#include <iostream>
using namespace std;
#include "linkedList.h"
int main()
{
linkedList l ;
for(int i =0;i<10;i++)
{
l.insert(30-(i+2),(i+1));
}
l.display();
cout<<endl;
linkedList plist ;
plist = l.bubbleSort();
plist.display();
return 0;
}