嵌入式单片机设计吧 关注:23贴子:95
  • 0回复贴,共1

数据结构 单项链表

只看楼主收藏回复

单项链表
typedef int ElementType;
struct Node;
typedef struct Node* PtrToNode;
typedef PtrToNode List;
typedef PtrToNode Position;
Position Header(List L);
Position First(List L);
Position Advance(Position P);//前进
ElementType Retrive(Position P);//检索
#endif
struct Node{
ElementType element;
Position next;
};
bool isEmpty(List L){
return L->next == NULL;
}
//是否是最后一个元素
bool isLast(Position P,List L){
return P->next == NULL;
}
//查找链表中的元素
Position ListFind(ElementType X,List L){
Position P;
P = L ->next;
while( P != NULL && P->element != X){
P = P->next;
}
return P;
}
//删除链表中X的元素
void Delete(ElementType X,List L){
Position P,TmpCell;
P = FindPrevious(X,L);
if(!isLast(P,L)){
TmpCell = P->next;
P->next = TmpCell->next;
free(TmpCell);
}
}
//查找X的前节点
Position FindPrevious(ElementType X,List L){
Position P;
P = L;
while( P->next != NULL && P->next->element != X){
P = P->next;
}
return P;
}
//在链表的位置P插入X元素
void ListInsert(ElementType X,List L,Position P){
Position TmpCell;
TmpCell = malloc(sizeof(struct Node));
if(TmpCell == NULL){
printf("Out of space\r\n");
}
TmpCell->element = X;
TmpCell->next = P->next;
P->next = TmpCell;
}
void DeleteList(List L){
Position P,TmpCell;
P = L->next;
L->next = NULL;
while( P != NULL){
TmpCell = P->next;
free(P);
P = TmpCell;
}
}
void Printf_List(List L){
int i = 0;
Position TmpCell;
TmpCell = L;
while(TmpCell->next != NULL){
printf("%d: %d\r\n",i,TmpCell->next->element);
i++;
TmpCell = TmpCell->next;
}
}
void Test_List(){
struct Node L_head = {.next = NULL};
Position p;
//L_head.next = NULL;
List L = &L_head;
ListInsert(1,L,&L_head);
ListInsert(2,L,&L_head);
ListInsert(3,L,&L_head);
ListInsert(4,L,&L_head);
Printf_List( L);
p = ListFind(3, L);
printf("p= %d\r\n",p->element);
Delete(3, L);
Printf_List( L);
}
int main2(){
Test_List();
}


IP属地:北京1楼2022-08-24 10:27回复