多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
### 定义 * 线性表的一种。通过物理结构的顺序存放来实现逻辑结构上的顺序特性。 * 可以通过数组实现。但由于直接的数组声明实现在栈中,不便于顺序表的操作处理。所以,通过在堆中动态分配一个连续内存单元的方式来实现顺序表的存储方式。 ### 代码实现 ``` #include <stdio.h> #include <stdlib.h> #include <assert.h> /** 顺序表的简单实现 */ #define SIZE (10) #define INCR (10) struct node { int *p; int allSize; int curPoint; }; typedef struct node *Node; /* 顺序表操作 */ void init(Node pNode); void insert(Node pNode,int value); void extend(Node pNode); int locate(Node pNode,int value); void del(Node pNode,int value); void print(Node pNode); void merge(Node p1,Node p2,Node pMerge); void init(Node pNode) { int *arr = (int *)malloc(sizeof(int) * SIZE); pNode->p = arr; pNode->allSize = SIZE; pNode->curPoint = 0; } void insert(Node pNode,int value) { int i,l; l = locate(pNode,value); if(pNode->allSize == pNode->curPoint) { extend(pNode); } for(i=pNode->curPoint;i>l;i--) { pNode->p[i] = pNode->p[i-1]; } pNode->p[l] = value; (pNode->curPoint)++; } void extend(Node pNode) { int *arr = (int *)malloc(sizeof(int) * (pNode->allSize + INCR)); int i; for(i=0;i<pNode->allSize;i++) { arr[i] = pNode->p[i]; } free(pNode->p); pNode->p = arr; pNode->allSize += INCR; } int locate(Node pNode,int value) { int i; if(pNode->curPoint == 0) return 0; for(i=0;i<pNode->curPoint;i++) { if(pNode->p[i] > value) { return i; } } } void del(Node pNode,int value) { //find->del->move int i,j; for(i=0;i<pNode->curPoint;i++) { if(pNode->p[i] == value) { //bingo for(j=i+1;j<pNode->curPoint;j++) { pNode->p[j-1] = pNode->p[j]; } i--; (pNode->curPoint)--; } } } void print(Node pNode){ int i; printf("allSize is %d;curPoint is %d\n",pNode->allSize,pNode->curPoint); for(i=0;i<pNode->curPoint;i++) { printf("number is %d,value is %d\n",i,pNode->p[i]); } } void merge(Node p1,Node p2,Node pMerge) { int i=0,j=0,t=0; pMerge->allSize = p1->allSize + p2->allSize; pMerge->p = (int *)malloc(sizeof(int) * (pMerge->allSize)); pMerge->curPoint = 0; while(i<p1->curPoint && j<p2->curPoint) { (pMerge->curPoint)++; if(p1->p[i] < p2->p[j]) { pMerge->p[t++] = p1->p[i++]; } else { pMerge->p[t++] = p2->p[j++]; } } while(i<p1->curPoint) { pMerge->p[t++] = p1->p[i++];(pMerge->curPoint)++; } while(j<p2->curPoint) { pMerge->p[t++] = p2->p[j++];(pMerge->curPoint)++; } } int main(int argc,char **argv) { //init the struct Node pNode = (struct node *)malloc(sizeof(struct node)); Node pNode1 = (struct node *)malloc(sizeof(struct node)); Node p = (struct node *)malloc(sizeof(struct node)); init(pNode); init(pNode1); insert(pNode,5); insert(pNode,4); insert(pNode,3); insert(pNode,2); insert(pNode,9); insert(pNode1,9); insert(pNode1,9); insert(pNode1,9); merge(pNode,pNode1,p); print(p); return 0; } ```