单链表(不带头结点)的输出,第一个元素似乎是地址值。
int main(){
LinkList L;
InitList(L);
int x, i = 1;
scanf("%d", &x);
while(x != 1111){
ListInsert(L, i, x);
i++;
scanf("%d", &x);
}
PrintList(L);
_Bool ListInsert(LinkList L, int i, int element){
//位序异常
if(i < 1){
return false;
}
//在第一位前插入数据
if(i == 1){
//不理解,L已经指向newData了,在此输出正常,但出了此函数就输出地址值
LNode *newData = (LNode *)malloc(sizeof(LNode));
newData->data = element;
newData->next = L;
L = newData;
printf("%d\n",L->data);
//L->data = element;
return true;
}
//寻找位序前一位元素
LNode *p;
int j = 1;
p = L;
while (p != NULL && j < i - 1)
{
p = p->next;
j++;
}
//以下部分可修改为
//return InsertNextNode(p, element);
//位序异常:超出长度
if(p == NULL){
return false;
}
//新数据插入单链表
LNode *newData = (LNode *)malloc(sizeof(LNode));
newData->data = element;
newData->next = p->next;
p->next = newData;
return true;
}
_Bool PrintList(LinkList L){
LNode *p = L;
while(p != NULL){
printf("%d->", p->data);
p = p->next;
}
printf("\n");
return true;
}
将第一个结点(i==1时候的特殊情况)的存储改为直接赋值 L->data = element; 这样是能正常存储读取第一个数的。
修改处见注释,供参考:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct node {
int data;
struct node* next;
}LNode, * LinkList;
void InitList(LinkList L);
bool ListInsert(LinkList* L, int i, int element); //修改
bool PrintList(LinkList L);
int main() {
LinkList L;
InitList(L);
int x, i = 1;
scanf("%d", &x);
while (x != 1111) {
ListInsert(&L, i, x); //修改
i++;
scanf("%d", &x);
}
PrintList(L);
return 0;
}
void InitList(LinkList L)
{
L = NULL;
}
bool ListInsert(LinkList* L, int i, int element) { //修改
//位序异常
if (i < 1) {
return false;
}
//在第一位前插入数据
if (i == 1) {
//不理解,L已经指向newData了,在此输出正常,但出了此函数就输出地址值
LNode* newData = (LNode*)malloc(sizeof(LNode));
newData->next = NULL; //修改
newData->data = element;
//newData->next = (*L); //修改
(*L) = newData; //修改
//printf("%d\n", L->data); //修改
//L->data = element;
return true;
}
//寻找位序前一位元素
LNode* p;
int j = 1;
p = (*L); //修改
while (p != NULL && j < i - 1)
{
p = p->next;
j++;
}
//以下部分可修改为
//return InsertNextNode(p, element);
//位序异常:超出长度
if (p == NULL) {
return false;
}
//新数据插入单链表
LNode* newData = (LNode*)malloc(sizeof(LNode));
newData->data = element;
newData->next = NULL; //修改
newData->next = p->next;
p->next = newData;
return true;
}
bool PrintList(LinkList L) {
int i = 0; //修改
LNode* p = L;
while (p != NULL) {
printf("%d->", p->data);
p = p->next;
i++; //修改
}
printf("\nLength:%d\n", i); //修改
return true;
}
我怎么没看到初始化链表的函数实现,不带头结点这个要事先处理好