双链表(非循环)相关操作:创建、析构、删除、冒泡排序

struct dulnode
{
    int val;
    dulnode *pre;
    dulnode *next;
};

//这里创建的不是双循环链表
dulnode* create_dulnode(int n)
{
    if (n <= 0) return NULL;

    int i = 0;
    dulnode *head, *p1, *p2;

    //生成头节点
    head = new dulnode;
    head->val = rand() % RAND_MAX;
    head->pre = NULL; //头节点前驱节点为空
    p1 = head;

    for ( i = 1; i < n; i++)
    {
        p2 = new dulnode;
        p2->val = rand() % RAND_MAX;

        p2->pre = p1;
        p1->next = p2;
        p1 = p2;
    }

    p1->next = NULL;
    return head;
}

void del_dulnode(dulnode* &head, const int num)
{
    //链表为空
    if (NULL == head) return;

    dulnode *temp, *p;

    //删除头节点
    while (head != NULL&&num == head->val)
    {
        temp = head;
        head = head->next;
        head->pre = NULL;
        delete temp;
        cout << "删除头节点:" << num << endl;
    }

    p = head;
    while (p != NULL)
    {
        if (num == p->val)
        {
            temp = p;
            p->pre->next = temp->next;
            p = temp->next;
            delete temp;
            cout << "删除节点:" << num << endl;
        }
        else
        {
            p = p->next;
        }
    }
}

void erase_dulnode(dulnode* head)
{
    if (NULL == head) return;

    dulnode *temp, *p = head;
    while (p)
    {
        temp = p;
        p = p->next;
        delete temp;
    }
}

void print_dulnode(dulnode* head)
{
    if (NULL == head) return;

    int i = 0;
    dulnode *p = head;
    while (p)
    {
        cout << " " << p->val << ",";
        p = p->next;
        
        if (5 == ++i)
        {
            i = 0;
            cout << endl;
        }
    }
    cout << endl;
}

int getdulnodelistlen(dulnode* head)
{
    if (NULL == head) return 0;

    int n = 0;
    dulnode* p=head;
    while (p)
    {
        ++n;
        p = p->next;
    }

    return n;
}

void sortdulnodelist(dulnode* head)
{
    //空双链表或者单节点双链表不做操作
    if (NULL == head || NULL == head->next) return;

    bool sign = false;
    int i, j, len = getdulnodelistlen(head), temp;
    dulnode *p;

    for (i = len - 1; i > 0; i--)
    {
        sign = false;
        p = head;
        for (j = 0; j < i; j++)
        {
            if (p->val > p->next->val)
            {
                temp = p->val;
                p->val = p->next->val;
                p->next->val = temp;

                sign = true;
            }

            p = p->next;
        }

        if (!sign) break; //此趟循环没有数值交换,排序已经完成
    }
}

 

posted @ 2015-08-04 21:39  从此寂静无声  阅读(381)  评论(0编辑  收藏  举报