선형 표 C 언어 배열 실현

//         ,   0  !
// 2019/12/1
// Leonwenbin

#include 
#include 

#define MAXLEN 100
#define ElementType int
#define Position int

struct LinearTable {
	ElementType elememts[MAXLEN];
	int last;
};

typedef struct LinearTable List;

List Create(ElementType arr[], int len) {
	List L;
	L.last = 0;
	for (int i = 0; i < len; i++) {
		L.elememts[i] = arr[i];
	}
	L.last = len - 1;
	return L;
}

List Insert(ElementType x, Position p, List L) {

	if (L.last >= MAXLEN - 1) {
		printf("Linear table is full
"); return; } if ((p > L.last + 1) || (p < 1)) { printf("Insert position is invalid
"); return; } for (Position q = L.last; q >= p; q--) { L.elememts[q + 1] = L.elememts[q]; } L.last++; L.elememts[p] = x; return L; } List Delete(Position p, List L) { if (p > L.last || p < 1) { printf("Delete position is invalid
"); return; } L.last = L.last - 1; int temp = L.elememts[p]; for (Position q = p; q <= L.last; q++) { L.elememts[q] = L.elememts[q + 1]; } printf("Deleted element is:%d
", temp); return L; } List DeleteAllSame(ElementType x, List L) { int cnt = 0; for (int i = 0; i <= L.last; i++) { if (L.elememts[i] == x) { for (int j = i + 1; j <= L.last; j++) { L.elememts[j - 1] = L.elememts[j]; } cnt++; } } L.last -= cnt; return L; } Position Locate(ElementType x, List L) { for (Position p = 0; p <= L.last; p++) { if (L.elememts[p] == x) { return p; } } printf("The specified element doesn't exit
"); return -1; } ElementType Retrieve(List L, int index) { if (index > MAXLEN || index < 0 || index > L.last) { printf("Index is invalid
"); return -1; } return L.elememts[index]; } List Reverse(List L) { if (L.last == 0 || L.last == 1) { return L; } int left = 0; int right = L.last; while (left <= right) { int temp = L.elememts[left]; L.elememts[left] = L.elememts[right]; L.elememts[right] = temp; left++; right--; } return L; } List destroy(List L) { L.last = 0; return L; } void printList(List L) { if (L.last == 0) { printf("Linear table is empty
"); return; } for (int i = 0; i <= L.last; i++) { printf("%d ", L.elememts[i]); } printf("
"); } int main(void) { ElementType arr[] = { 1,2,3,4,5 }; int len = sizeof(arr) / sizeof(ElementType); List L = Create(arr, len); printList(L); printf("%d
", L.last); L = Insert(11, 4, L); printList(L); printf("%d
", L.last); L = Insert(11, 4, L); printList(L); printf("%d
", L.last); L = Insert(11, 4, L); printList(L); printf("%d
", L.last); L = Reverse(L); printList(L); L = Delete(6, L); printList(L); printf("DeleteAll:"); L = DeleteAllSame(11, L); printList(L); printf("position = %d
", Locate(1, L)); printf("value[%d] = %d
", 4, Retrieve(L, 4)); L = destroy(L); printList(L); system("pause"); return 0; }

좋은 웹페이지 즐겨찾기