顺序表实现增删查改
代码
#include <iostream>
#include <cstdio>
using namespace std;
typedef int ElemType; // Assume the elements of linear list to be of type integer
#define LIST_SIZE 1024 // Assume that the maximum length of a linear list is 1024
#define FALSE 0
#define TRUE 1
typedef struct {
ElemType data[LIST_SIZE];
int last; // Specify the location of the last node
} SeqList;
int Insert_SeqList(SeqList * LPtr, ElemType x, int k); // ~
int Delete_SeqList(SeqList * LPtr, int k);
int Locate_SeqList( SeqList * LPtr, ElemType key );
int Get_SeqList( SeqList * LPtr, int i, ElemType * e);
void Print_SeqList(SeqList * LPtr);
void Input_SeqList(SeqList * LPtr, int n); // n elements
int main() {
int n; // n elements
cin >> n;
SeqList int_seq;
SeqList * LPtr = &int_seq; // A pointer to structure SequenList
Input_SeqList( LPtr, n );
//int Insert_SeqList(SeqList * LPtr, ElemType x, int k);
//Insert_SeqList(LPtr, 100, 3);
Print_SeqList( LPtr );
Insert_SeqList(LPtr, 100, 3);
Print_SeqList( LPtr );
// Delete_SeqList(LPtr, 3);
// Print_SeqList(LPtr);
cout << Locate_SeqList(LPtr, 100) << endl;
int e;
if ( Get_SeqList(LPtr, 3, &e) ) cout << e << endl;
return 0;
}
int Insert_SeqList(SeqList * LPtr, ElemType x, int k) { // k, the index of the position waiting for action of inserting
int j;
if (LPtr->last >= LIST_SIZE - 1) return FALSE; // overflow
else if ( k < 0 || k >= (LPtr->last + 1)) return FALSE; // Illegal location
else {
for ( j = LPtr->last; j >= k; j-- ) { // Start with the last element of the order list
LPtr->data[j + 1] = LPtr->data[j]; // Move last - k elements back
}
LPtr->data[k] = x; // Put x in the postition k
LPtr->last = LPtr->last + 1; // Motifies the value of last of the last node pointer
}
return TRUE;
}
int Delete_SeqList(SeqList * LPtr, int k) {
if ( ( k > 0 && k <= LPtr->last ) && ( LPtr->last != -1 ) ) {
for ( int j = k; j <= LPtr->last - 1; j++ ) { // LPtr->last - 1 !!!
LPtr->data[j] = LPtr->data[j + 1];
}
LPtr->last--;
return TRUE; // Successfully deleted
}
return FALSE; // Abnormal findings
}
int Locate_SeqList( SeqList * LPtr, ElemType key ) {
for ( int i = 0; i <= LPtr->last; i++ ) {
if ( LPtr->data[i] == key ) return i;
}
return -1;
}
int Get_SeqList( SeqList * LPtr, int i, ElemType * e) { // Get the value stored in the index i of data
if ( i < 0 || i > LPtr->last ) return FALSE;
if ( LPtr->last < 0 ) return FALSE;
*e = LPtr->data[i];
return TRUE;
}
void Print_SeqList(SeqList * LPtr) {
int i;
int j = 0;
for ( i = 0; i <= LPtr->last - 1; i++ ) {
j++;
cout << LPtr->data[i] << '\t';
if ( !( j % 10 ) ) cout << '\n';
}
cout << LPtr->data[i];
if ( !( j % 10 ) )
cout << '\n';
cout << '\n';
}
void Input_SeqList(SeqList * LPtr, int n) {
for ( int i = 0; i < n; i++ ) {
cin >> LPtr->data[i];
}
LPtr->last = n - 1;
}
小结
Segmentation fault (core dumped)
该错误应该是由指针没有初始化,未指向具体地址造成的。