顺序存储
# include <iostream>
using namespace std;
# define MaxSize 50
template < typename ElemType >
struct sqList { ElemType data[ MaxSize] ; int length;
} ;
# ifdef DEBUG
# define InitSize 100
template < typename ElemType >
struct seqList { ElemType* data; int MaxSize; int length;
} ;
# endif
template < typename ElemType >
bool ListInsert ( sqList< ElemType> & L, int i, ElemType e) { if ( i< 1 || i> L. length + 1 ) return false ; if ( L. length >= MaxSize) return false ; for ( int j = L. length; j >= i; -- j) { L. data[ j] = L. data[ j - 1 ] ; } L. data[ i - 1 ] = e; ++ L. length; return true ;
}
template < typename ElemType >
bool ListDelete ( sqList< ElemType> & L, int i, ElemType& e) { if ( i< 1 || i> L. length) return false ; e = L. data[ i - 1 ] ; for ( int j = i ; j < L. length; ++ j) { L. data[ j - 1 ] = L. data[ j] ; } -- L. length; return true ;
}
template < typename ElemType >
int LocalElem ( sqList< ElemType> & l, ElemType& e) { int i; for ( i = 0 ; i < l. length; ++ i) { if ( l. data[ i] == e) return i + 1 ; } return 0 ;
}
链式存储
# include <iostream>
using namespace std;
template < typename ElemType >
struct LNode { ElemType data; struct LNode * next;
} ;
template < typename ElemType >
LNode< ElemType> * List_HeadInsert ( LNode< ElemType> * L) { LNode< ElemType> * s; ElemType x; L = new LNode< ElemType> ; L-> next = nullptr ; cin >> x; while ( x != 9999 ) { s = new LNode< ElemType> ; s-> data = x; s-> next = L-> next; L-> next = s; cin >> x; } return L;
}
template < typename ElemType >
LNode< ElemType> * List_TailInsert ( LNode< ElemType> * L) { ElemType x; L = new LNode< ElemType> ; LNode< ElemType> * s, * r = L; cin >> x; while ( x != 9999 ) { s = new LNode< ElemType> ; s-> data = x; r-> next = s; r = s; cin >> x; } r-> next = nullptr ; return L;
}
template < typename ElemType >
LNode< ElemType> * GetElem ( LNode< ElemType> * L, int i) { if ( i < 1 ) return nullptr ; int j = 1 ; LNode< ElemType> * p = L-> next; while ( p != nullptr && j < i) { p = p-> next; ++ j; } return p;
}
template < class ElemType >
LNode< ElemType> * LocateElem ( LNode< ElemType> * L, ElemType e) { LNode< ElemType> * p = L; while ( p!= nullptr && p-> data!= e) { p = p-> next; } return p;
}
template < class ElemType >
bool Front_Insert ( LNode< ElemType> * L, int i, ElemType e) { LNode< ElemType> * temp = GetElem ( L, i - 1 ) ; if ( temp == nullptr ) return false ; LNode< ElemType> * newNode = new LNode< ElemType> ; newNode-> data = e; newNode-> next = temp-> next; temp-> next = newNode; return true ;
}
template < class ElemType >
bool Delete ( LNode< ElemType> * L, int i) { LNode< ElemType> * temp = GetElem ( L, i - 1 ) ; if ( temp == nullptr ) return false ; LNode< ElemType> * next = temp-> next; temp-> next = temp-> next-> next; delete next; return true ;
}
template < class ElemType >
int GetLinkLength ( LNode< ElemType> * L) { int cnt = 0 ; LNode< ElemType> * cur = L-> next; while ( cur) { ++ cnt; cur = cur-> next; } return cnt;
}