#pragma once
#ifndef _MY_LIST
#define _MY_LIST
#include "iostream"
using namespace std;
struct ListNode
{
int data;
ListNode * next;
};
class MyList
{
public:
MyList();
~MyList();
void init(int num);
void TraverseList();
void pustBack(int value);
void sortList();
void deleteOne(int value);
void clearList();
private:
ListNode * head;
int count;
};
#endif // !_MY_LIST
源文件
#include "stdafx.h"
#include "MyList.h"
MyList::MyList()
{
this->head = new ListNode();
this->head->data = 0;
this->head->next = nullptr;
this->count = 0;
}
MyList::~MyList()
{
delete this->head;
this->head = nullptr;
this->count = 0;
cout << "~MyList()" << endl;
}
void MyList::init(int num)
{
for (size_t i = 0; i < num; i++)
{
ListNode * next = this->head;
while (next->next != nullptr)
{
next = next->next;
}
ListNode * p = new ListNode();
int n = num - i;
p->data = n;
p->next = nullptr;
next->next = p;
this->count++;
}
}
void MyList::TraverseList()
{
ListNode * next = this->head->next;
while (next)
{
cout << next->data << ",";
next = next->next;
}
cout << endl;
}
void MyList::pustBack(int value)
{
ListNode * tmp = new ListNode();
tmp->data = value;
tmp->next = nullptr;
ListNode * next = this->head;
while (next->next != nullptr)
{
next = next->next;
}
next->next = tmp;
this->count++;
}
void MyList::sortList()
{
if (this->count == 0) return;
ListNode * firstNode = this->head->next;
// 9,8,7,6,5,4,3,2,1,10
ListNode * p = nullptr, *q = nullptr, *tail = nullptr;
for (size_t i = 0; i < this->count - 1; i++)
{
int num = this->count - i - 1;
tail = this->head;
p = tail->next;
q = p->next;
while (num--)
{
if (p->data > q->data) {
p->next = q->next;
q->next = p;
tail->next = q;
}
tail = tail->next;
p = tail->next;
q = p->next;
}
}
}
void MyList::deleteOne(int value)
{
if (this->count == 0)return;
ListNode * head = this->head;
ListNode * p = head->next;
while (p != nullptr)
{
if (p->data == value) {
head->next = p->next;
delete p;
p = nullptr;
this->count--;
break;
}
head = head->next;
p = p->next;
}
}
void MyList::clearList()
{
if (this->count == 0) return;
ListNode * head = this->head;
ListNode * next = head->next;
while (next != nullptr)
{
next->data = 0;
head->next = next->next;
next->next = nullptr;
next = head->next;
this->count--;
}
}
// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "iostream"
#include "MyList.h"
using namespace std;
int main()
{
MyList * list = new MyList();
list->init(8);
list->pustBack(10);
list->sortList();
list->deleteOne(5);
list->clearList();
list->TraverseList();
delete list;
list = nullptr;
system("pause");
return 0;
}