第3周实践项目4 -顺序表的应用 删除顺序表中元素为x的值
生活随笔
收集整理的這篇文章主要介紹了
第3周实践项目4 -顺序表的应用 删除顺序表中元素为x的值
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
/*
copyright (t) 2017,煙臺大學計算機學院
*All rights reserved.
*文件名稱:1.cpp
*作者:邵雪源
*完成日期:2017年9月14日
*問題描述:刪除元素在x,的所有元素,要求算法的時間按復雜度為o(n),空間復雜度為o(1)
*版本號:v1.0
*/main.cpp
#include "list.h"
#include <stdio.h>
void delnode1(SqList *&L,ElemType x)
{int i;ElemType e;while((i=LocateElem(L,x))>0){ListDelete(L, i, e);}
}
//用main寫測試代碼
int main()
{SqList *sq;ElemType a[10]= {5,8,7,0,2,4,9,6,7,3};CreateList(sq, a, 10);printf("刪除前 ");DispList(sq);delnode1(sq, 7);printf("刪除后 ");DispList(sq);return 0;
}
list.h
#ifndef LIST_H_INCLUDED
#define LIST_H_INCLUDED
#define MaxSize 50
typedef int ElemType;
typedef struct
{ElemType data[MaxSize];int length;
} SqList;
void CreateList(SqList *&L, ElemType a[], int n);//用數組創建線性表
bool ListEmpty(SqList *L);//判定是否為空表ListEmpty(L)
void DispList(SqList *L);//輸出線性表DispList(L)
bool GetElem(SqList *L,int i,ElemType &e);//求某個數據元素值GetElem(L,i,e)
int LocateElem(SqList *L, ElemType e);//按元素值查找LocateElem(L,e)
bool ListDelete(SqList *&L,int i,ElemType &e);//刪除數據元素ListDelete(L,i,e)#endif // LIST_H_INCLUDED
#endif
list.cpp
#include <stdio.h>
#include <malloc.h>
#include "list.h"
//用數組創建線性表
void CreateList(SqList *&L, ElemType a[], int n)
{int i;L=(SqList *)malloc(sizeof(SqList));for (i=0; i<n; i++)L->data[i]=a[i];L->length=n;
}
//判定是否為空表ListEmpty(L)
bool ListEmpty(SqList *L)
{return(L->length==0);
}
//輸出線性表DispList(L)
void DispList(SqList *L)
{int i;if (ListEmpty(L)) return;for (i=0; i<L->length; i++)printf("%d ",L->data[i]);printf("\n");
}
//求某個數據元素值GetElem(L,i,e)
bool GetElem(SqList *L,int i,ElemType &e)
{if (i<1 || i>L->length) return false;e=L->data[i-1];return true;
}
//按元素值查找LocateElem(L,e)
int LocateElem(SqList *L, ElemType e)
{int i=0;while (i<L->length && L->data[i]!=e) i++;if (i>=L->length) return 0;else return i+1;
}
//刪除數據元素ListDelete(L,i,e)
bool ListDelete(SqList *&L,int i,ElemType &e)
{int j;if (i<1 || i>L->length) //參數錯誤時返回falsereturn false;i--; //將順序表邏輯序號轉化為物理序號e=L->data[i];for (j=i; j<L->length-1; j++) //將data[i..n-1]元素前移L->data[j]=L->data[j+1];L->length--; //順序表長度減1return true; //成功刪除返回true
}
解法二:
#include "list.h"
#include <stdio.h>
void delnode2(SqList *&L,ElemType x)
{int k=0,i; //k記錄非x的元素個數for (i=0; i<L->length; i++)if (L->data[i]!=x){L->data[k]=L->data[i];k++;}L->length=k;
}
//用main寫測試代碼
int main()
{SqList *sq;ElemType a[10]= {5,8,7,0,2,4,9,6,7,3};CreateList(sq, a, 10);printf("刪除前 ");DispList(sq);delnode2(sq, 7);printf("刪除后 ");DispList(sq);return 0;
}
總結
以上是生活随笔為你收集整理的第3周实践项目4 -顺序表的应用 删除顺序表中元素为x的值的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 第3周 实践项目2 建设”顺序表“算法
- 下一篇: SDUT_2121数据结构实验之链表六: