考研数据结构(每日一题)
题目:(1)使用头插法建立单链表
(2)使用尾插法建立单链表
算法图解:
完整代码:
Linklist List_HeadInsert(Listlist &L){
LNode *s; //标记需要插入的结点
int x; //传入结点中data域的值
L = (Linklist) malloc (sizeof(LNode)); //创建头结点
scanf("%d",&x);
while(x != -1){
s = (LNode*) malloc (sizeof(LNode));
s -> data = x; //赋值
s -> next = L -> next; //将新结点插入
L -> next = s;
}
return L;
}
Linklist List_TailInsert(Listlist &L){
LNode *s,*r = L;
int x; //传入结点中data域的值
L = (Linklist) malloc (sizeof(LNode));
scanf("%d",&x);
while(x != -1){
s = (LNode*) malloc (sizeof(LNode));
s -> data = x; //赋值
r -> next = s;
r = s;
}
r -> next = null; //表尾的next置空
return L;
}