1. 程式人生 > >按遞增次序輸出帶頭節點單鏈表的資料元素並釋放其空間

按遞增次序輸出帶頭節點單鏈表的資料元素並釋放其空間

#include "stdafx.h"
#include<stdio.h> 
#include<malloc.h> 
#include<stdlib.h>
typedef int type;
typedef struct lnode //定義連結串列結點的資料結構 
{
    int data;
    struct lnode *next;
}Lnode;
typedef Lnode node;
typedef struct dnode//定義雙鏈表結點的資料結構 
{
    int data;
    struct dnode *lnext;
    struct dnode *rnext;
}Dnode;
int  posprint9(node *h)
{
    //先將連結串列就地使用插入的方法排好序再一次輸出並釋放空間
    node *p = h->next; node *q = p;
    while (q->next)//插入法排好正序 
    if (q->next->data >= q->data)
        q = q->next;
    else
    {
        if (q->next->data <= p->data)
        {
            h->next = q->next;
            q->next = q->next->next;
            h->next->next = p;
            //  print(h);
        }
        else
        {
            while (!(p->data <= q->next->data&&p->next->data >= q->next->data))
                p = p->next;
            node *tem = p->next;
            p->next = q->next;
            q->next = q->next->next;
            p->next->next = tem;
            //  print(h);
        }
        p = h->next;
    }
    //列印節點值並釋放結點所佔有的空間
    p = h;
    q = h->next;
    while (q)
    {
        printf("%d ", q->data);
        p = q; q = q->next;
        free(p);
    }
    free(h);
    //分析以上程式可知其時間複雜度花在遍歷整個連結串列以及找到應插入位置的兩個迴圈上,最差為o(n^2) 空間複雜度o(1);
    //方法二:每次找到當前連結串列的最小值後則進行刪除,重複以上操作直至連結串列中一個元素也不剩
    //   node *p,*q,*tem;
    //   while(h->next){
    //   p=h;q=p->next;
    //   while(q->next)
    //   {
    //   if(q->next->data<p->next->data)
    //     p=q;
    //   else
    //   q=q->next;
    //   }
    //   printf("%d ",p->next->data);
    //   tem=p->next;
    //   p->next=p->next->next;
    //   free(tem)
    //}
    //   free(h);
    return 0;
}