#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
typedef struct LNode{
ElemType data ;
struct LNode *next;
}LNode,*LinkList;
bool List_HeadInsert(LinkList &L){ //利用头插法建立单链表
LNode *s;int x ;
L = (LNode *)malloc(sizeof(LNode));
L->next = NULL;
scanf("%d",&x);
while(x!=9){
s=(LNode*)malloc(sizeof(LNode));
s->data = x;
s->next = L->next;
L->next = s;
scanf("%d",&x);
}
return L;
}
bool ListInsert(LinkList &L,int i,ElemType e){
if(i<1)
return false;
LNode *p;
int j = 0;
p = L;
while(p != NULL && j<i-1){
p=p->next;
j++;
}
if(p==NULL)
return false;
LNode *s = (LNode *)malloc(sizeof(LNode));
s->data = e;
s->next = p->next;
p->next = s;
return true;
}
void PrintList(LinkList &L) { //对单链表进行打印
printf("该链表的内容为:");
while (L->next != NULL) {
printf("%d", L->next->data);
L = L->next;
}
printf("\n");
}
int main(){
LinkList L;
List_HeadInsert(L);
ListInsert(L,3,3);
PrintList(L);
}
单链表用头插链表法创建新表、插入元素、打印
最新推荐文章于 2024-07-24 12:42:40 发布