有序的双向链表

来源:互联网 发布:网络高清硬盘播放机 编辑:程序博客网 时间:2024/05/29 19:43

摘要

链表是一种物理结构上不连续,非顺序的数据结构,其逻辑顺序结构是以结点内的指针来确定的,此篇文章实现一个特殊的链表结构,其中的元素在插入时就是有序的排列。

分析

要实现有序的链表,必然要比较链表内数据的大小,然后在合适的地方插入。当判断到某一点可插入时进行插入。可选择单向链表实现,但每次判断需要保存上一点的信息。这里使用双向链表结构来实现。
每个节点保存的信息:存储内容、前一个节点指针、后一个节点指针

具体实现

代码

SortedLinkedList.h
#pragma once#include<iostream>using namespace std;template<typename T>//节点信息struct Node{    T item;    Node* next;    Node* pre;    Node<T>(T item) {        this->item = item;        this->next = NULL;        this->pre = NULL;    }};template<typename T>class LinkedList{public:    LinkedList();    ~LinkedList();    void insert(T item);    void printList();private:    void _insert(Node<T>* head, Node<T>* temp);    void _printList(Node<T>* head);    //头结点    Node<T>* head;    //节点总数    int count;    //插入节点数值相同数量    int sameCount;};
SortedLinkedList.cpp
#include "LinkedList.h"template<typename T>LinkedList<T>::LinkedList(){    this->head = NULL;    this->count = 0;    this->sameCount = 0;}template<typename T>LinkedList<T>::~LinkedList(){    delete this->head;    this->head = NULL;}template<typename T>void LinkedList<T>::insert(T item){    Node<T>* temp = new Node<T>(item);    if (this->head == NULL) {        this->head = temp;        this->count = 1;    }    else {        _insert(this->head, temp);    }}template<typename T>void LinkedList<T>::printList(){    cout << "START<->";    _printList(this->head);    cout << endl << "含有" << this->sameCount << "个重复值"<<endl;}/*    head最初为头结点    temp为插入的节点*/template<typename T>void LinkedList<T>::_insert(Node<T>* head, Node<T>* temp){    if (head==NULL) {        head = temp;        this->count += 1;    }    else {        if (head->item < temp->item) {            if (head->next == NULL) {                head->next = temp;                temp->pre = head;                this->count += 1;            }            else {                _insert(head->next, temp);            }        }        else if(head->item == temp->item){            this->sameCount += 1;        }        else {            //头结点            if (head->pre == NULL) {                temp->next = head;                head->pre = temp;                this->head = temp;                this->count += 1;            }            else {                temp->next = head;                temp->pre = head->pre;                head->pre->next = temp;                head->pre = temp;                this->count += 1;            }        }    }}/*    打印整个链表*/template<typename T>void LinkedList<T>::_printList(Node<T>* head){    if (head == NULL) {        cout << "DONE" << endl;    }    else {        cout << head->item <<"<->";        _printList(head->next);    }}void main(){    LinkedList<int>* s = new LinkedList<int>();    int p[] = {5,6,8,2,6,9,1,7,6,6,6,6,6,6};    int count = sizeof(p) / sizeof(int);    for (int i = 0; i < count; i++) {        s->insert(p[i]);    }    s->printList();    system("pause");}
输出

这里写图片描述