- #include <iostream>
- #include <stack>
- using namespace std;
- class Linklist
- {
- private:
- typedef struct NODE
- {
- int data;
- NODE* next;
- NODE(int data, NODE* next)
- {
- this->data = data;
- this->next = next;
- }
- };
- private:
- NODE* head;
- public:
- //默认构造函数
- Linklist(int n=10)
- {
- NODE* p = new NODE(-1,0);
- head = p;
- int i = 0;
- while (i<n)
- {
- int k = 0;
- cout << "input the NODE of " << i+1 << ":";
- cin >> k;
- NODE* t_ptr = new NODE(k,0);
- p->next = t_ptr;
- p = p->next;
- i++;
- }
- }
- //析构函数
- ~Linklist()
- {
- stack<NODE*> ptr_stack;
- NODE* ptr = head;
- while (0 != ptr)
- {
- ptr_stack.push(ptr);
- ptr = ptr->next;
- }
- while (!ptr_stack.empty())
- {
- delete ptr_stack.top();
- ptr_stack.pop();
- }
- }
- //打印链表
- void display()
- {
- NODE* p = head->next;
- while (0 != p)
- {
- cout << (p->data) << endl;
- p = p->next;
- }
- }
- //链表反转
- void antitone()
- {
- stack<NODE*> ptr_stack;
- NODE* ptr = head->next;
- while (ptr)
- {
- ptr_stack.push(ptr);
- ptr = ptr->next;
- }
- head->next = ptr_stack.top();
- ptr_stack.pop();
- ptr = head->next;
- ptr->next = 0;
- while (!ptr_stack.empty())
- {
- ptr->next = ptr_stack.top();
- ptr_stack.pop();
- ptr = ptr->next;
- ptr->next = 0;
- }
- }
- //数据data第一次出现的后面插入一个节点
- bool insertNODE(int data)
- {
- NODE* ptr = get_ptr(data);
- if (ptr)
- {
- cout << "input the data of you wanna insert:";
- int k = 0;
- cin >> k;
- NODE* node = new NODE(k,0);
- node->next = ptr->next;
- ptr->next = node;
- return true;
- }
- return false;
- }
- //获得节点的个数
- int getDataNum()
- {
- NODE* ptr = head->next;
- int num=0;
- while(ptr)
- {
- num++;
- ptr = ptr->next;
- }
- return num;
- }
- //链表排序
- void sort()
- {
- int num = getDataNum();
- int* arr = new int[num];
- NODE* ptr = head->next;
- for (int i = 0; i<num; i++)
- {
- arr[i] = ptr->data;
- ptr = ptr->next;
- }
- //冒泡
- for (int i=0; i<num; i++)
- for (int j=i+1; j<num; j++)
- if(arr[i]>arr[j])
- {
- int tmp = arr[j];
- arr[j] = arr[i];
- arr[i] = tmp;
- }
- ptr = head->next;
- for (int i=0; i< num; i++)
- {
- ptr->data = arr[i];
- ptr = ptr->next;
- }
- delete []arr;
- }
- //删除data第一次出现的节点
- bool deleteNODE(int data)
- {
- NODE* ptr_1 = head;
- NODE* ptr_2 = head->next;
- while (ptr_2 && (ptr_2->data != data))
- {
- ptr_1 = ptr_1->next;
- ptr_2 = ptr_2->next;
- }
- if (ptr_2)
- {
- ptr_1->next = ptr_1->next->next;
- delete ptr_2;
- return true;
- }
- return false;
- }
- private:
- //获得数据为data第一次出现的节点的指针值
- NODE* get_ptr(int data)
- {
- NODE* ptr = head->next;
- while (ptr&&((ptr->data) != data))
- ptr = ptr->next;
- if (!ptr)
- return 0;
- return ptr;
- }
- };
- int main()
- {
- Linklist linklist = Linklist(20);
- linklist.display();
- linklist.sort();
- cout << "---------/n";
- linklist.display();
- return 0;
- }
一个简单的链表类
最新推荐文章于 2023-02-21 16:36:12 发布