双向链表的排序,单向链表的反转

1.  采用的方案:冒泡排序

   和数组的冒泡排序的思想没有很大的区别。直接 看代码吧。

   定义一下数据结构:

typedef struct student
{
    int num;
    float score;
    struct student *pre;
    struct student *pnext;
}node,*Node;

   排序代码:

Node sortt(Node head)
{
    Node p=head,pn=head;
    for(int i=0;i<n-1;i++)
    {
        p=head->next;
        pn=p->next;//p和pn总是两个相邻的节点,且pn在p之后
        for(int j=0;j<n-i-1;j++)
        {
            if(p->score > pn->score)
            {
                if(pn->next==NULL)
                {
                    p->next=NULL;
                    pn->pre=p->pre;
                    p->pre->next=pn;
                    pn->nextt=p;
                    p->pre=pn;
                }
                else
                {
                    p->next=pn->next;
                    pn->pre=p->pre;
                    p->pre->next=pn;
                    pn->next->pre=p;
                    p->pre=pn;
                    pn->next=p;
                    //位置交换结束
                    pn=p->next;//位置交换结束之后进行指针偏移,pn指向p的下一个节点
                }
            }
            else
            {
                p=p->next;
                pn=pn->next;
            }
        }
    }
    return head;
}

 

void TwoWayBubbleSort(LinkList &L)
{
    int exchange = 1;//设标记
    LinkList head = L;//双向链表头,算法过程中是向下起泡的开始结点
    LinkList tail = NULL;//双向链表尾,算法过程中是向上起泡的开始结点
    while(exchange)
    {
        LinkList p = head->next;
        exchange = 0;
        while (p->next != tail)
        {
            if (p->data > p->next->data)
            {
                LinkList temp = p->next; exchange = 1;
                p->next = temp->next; 
                if(temp->next)temp->next->prior = p;
                temp->next = p; p->prior->next = temp;
                temp->prior = p->prior; p->prior = temp;
            }
            else p = p->next;
        }
        tail = p;
        p = tail->prior;
        while (exchange&&p->prior != head)
        {

            if (p->data < p->prior->data)
            {
                LinkList temp = p->prior; exchange = 1;
                p->prior = temp->prior; temp->prior->next = p;
                temp->prior = p; p->next->prior = temp;
                temp->next = p->next; p->next = temp;
            }
            else p = p->prior;
        }
            head = p;
    }
}

 

2.  保证不断链,每遍历一下就变换链的方向

   定义数据结构:

struct ListNode {
     int val;
     ListNode *next;
     ListNode(int x) : val(x), next(NULL) {}
 };

   代码:

ListNode* reverseList(ListNode* head) {
        ListNode *ans=NULL;
        ListNode *pre=NULL;
        ListNode *temp=head;
        while(temp!=NULL)
        {
            ListNode *nextt=temp->next;
            if(nextt==NULL)
                ans=temp;
            temp->next=pre;
            pre=temp;
            temp=nextt;
        }
        return ans;
    }

 

上一篇:oracle connect by用法


下一篇:1.4 双向循环链