1. 程式人生 > 其它 >資料結構習題_2.10

資料結構習題_2.10

2.10 指出以下演算法的錯誤和低效(即費時)之處,並將它改寫為一個既正確又高效的演算法。

Status  DeleteK(SqList &a, int i, int k)
    {//本過程從順序儲存結構的線性表a中刪除第i個元素起的k個元素
        if(i<1 || k<0 || i+k>a.length)
            return INFEASIBLE;              //引數不合法
        else
            for(count=1; count<k; count++)
            {//刪除一個元素
for(j=a.length; j>=i+1; j--) a.elem[j-1] = a.elem[j]; a.length--; } return OK; }//DeleteK

正確的演算法思路(以i=3 k=3為例):

演算法實現:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define LIST_INIT_SIZE 100
#define
ERROR 0; #define OK 1; typedef int ElemType; typedef int Status; typedef struct { ElemType elem[LIST_INIT_SIZE]; int length; }SqList;//順序表 Status test_2_10(SqList *s, int i, int k) { int j; if(i<1 || i>s->length || k<0 || i+k-1>s->length) return ERROR;
for ( j = i+k; j <= s->length; j++) s->elem[j-k-1] = s->elem[j-1]; s->length -= k; return OK; }

優點:一次性刪除k個元素,無需大量移動元素