天勤論壇高分筆記 2016 版,第 27 頁,例 2-2。
描述:刪除順序表L中下標爲p(1<=p<=length)的元素,成功返回1,不然返回0,並將被刪除元素的值賦給e。c++
c/* Page 27, Example 2-2. 描述:刪除順序表L中下標爲p(1<=p<=length)的元素,成功返回1,不然返回0,並將被刪除元素的值賦給e。 */ #include "stdio.h" #define MAXSIZE 50 typedef struct { int data[MAXSIZE]; int length; }Sqlist; void init(Sqlist &sl) { int len = 10; for(int i=1; i<=len; ++i) { sl.data[i] = i*3-2; } sl.length = len; } int delSqlist(Sqlist &sl, int index, int &e) { int len=sl.length; int loc; if(index<1 || index>len) { return 0; } loc=index; e=sl.data[index]; //返回被刪除的值應在「刪除」(後續元素前移)前進行 while(loc<len) { sl.data[loc]=sl.data[loc+1]; loc++; // 這步不能遺漏 } sl.length=len-1; return 1; } void printSqlist(Sqlist sl) { int len=sl.length; for(int i=1; i<=len; i++){ printf("%d,", sl.data[i]); } printf(";Length: %d\n", sl.length); } int main() { int index; int e; Sqlist sl; init(sl); printf("Index: "); scanf("%d", &index); printSqlist(sl); if(delSqlist(sl, index, e) == 1) { printf("Deleted finish! Deleted value is %d. \n", e); } else { printf("Deleted failed. \n"); } printSqlist(sl); return 0; }