順序表的建立、輸入、輸出、查找、插入、刪除(數據結構)


1.順序表的基本操作實踐。

(1)建立4個元素的順序表list[]={2,3,4,5},實現順序表建立的基本操作。

(2)在list[]={2,3,4,5}的元素4和5之間插入一個元素9,實現順序表插入的基本操作。

(3)在list[]={2,3,4,9,5}中刪除指定位置(i=3)上的元素4,實現順序表的刪除的基本操作。

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#define MAXSIZE 10
using namespace std;

typedef int ElemType;
typedef struct {
    ElemType a[MAXSIZE];
    int length;
} S;
void CreatList(S &L) {
    scanf("%d", &L.length);
    for(int i = 1; i <= L.length; i ++) scanf("%d",&L.a[i]);
}   //創建列表
void PutList(S L) {
    for(int i = 1; i <= L.length; i ++) {
        printf("%d ",L.a[i]);
    }
    printf("\n");
}  //輸出列表
void InserElem(S &L, int i, ElemType x) {               j i
    if(i < 1 || i > L.length) return;             2 3 4 5 9
    for(int j = L.length+1; j > i; j --) {              j-1  j
        L.a[j] = L.a[j-1];                        2 3 4 9 5
    }
    L.a[i] = x;
    L.length++;
} //插入
void DeleElem(S &L, int i) {
    for(int j = i; j < L.length; j ++) {
        L.a[j] = L.a[j+1];                         j j+1
    }                                          2 3 4 9 5
    L.length--;
}//刪除int main() {
    S L;
    CreatList(L);
    InserElem(L,4,9);
    PutList(L);
    DeleElem(L,3);
    PutList(L);
    return 0;
}

結果

E:\c++>b
4
2 3 4 5
2 3 4 9 5
2 3 9 5

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM