链表的问题,代码有点长,谢谢指点的前辈
我的是在vs2017写的,可能有些地方有差异,望大佬指点;头文件
#pragma once
typedef struct SingleNode
{
ElemType data;
struct SingleNode *next;
}SingleLinkedList, *LinkList;
void ListInitialize(SingleLinkedList**head)/*单链表初始化*/
{ /*我对传递二级指针的理解,形参一级指针传递值,二级指针传地址,emm,可能也不是这样理解*/
if ((*head = (SingleLinkedList *)malloc(sizeof(SingleLinkedList))) == NULL)/*这里*head是地址*/
exit(1);
(*head)->next = NULL;
}
int ListLength(SingleLinkedList *head)/*获得线性表的长度*/
{
SingleLinkedList *p = head;
int size = 0;
while (p->next != NULL)
{
p = p->next;
size++;
}
return size;
}
int ListGet(SingleLinkedList *head, int i, ElemType *x)/*取序号为i的元素的值*/
{
SingleLinkedList *p;
int j;
p = head;
j = -1;
while (p->next != NULL && j < i)
{
p = p->next;
j++;
}
if (j != i)
{
printf("取元素位置参数错!");
return 0;
}
*x = p->data;
return 1;
}
void ListInsert(SingleLinkedList *head, ElemType x)/*插入数据元素*/
{
SingleLinkedList *p, *q, *t;
t = (SingleLinkedList*)malloc(sizeof(SingleLinkedList));
t->data = x;
p = head, q = head->next;
while (q != NULL && q->data < x)
{
p = q, q = q->next;
}
/*for (p = head, q = head->next; q != NULL && q->data < x; p = q, q = q->next)
{
//写法2
}*/
p->next = t;
t->next = q;
}
int ListDelete(SingleLinkedList *head, ElemType x)/*删除元素*/
{
SingleLinkedList *p, *s;
p = head;
s = p->next;
while (s != NULL && s->data < x)
{
p = s; s = s->next;
}
if (s->data != x)
return 0;
p->next = s->next;
return 1;
} 头文件的注释各位大神不用理,自己写来理解的;
源文件
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef int ElemType;
#include"LinkedList.h"
int main()
{
LinkList head;
int i,j, x,s1,s2;
ListInitialize(&head);
for (j= 0; j< 10; j ++)/*j用于输入的数据*/
{
ListInsert(head, j);
}
for (i = 0; i < ListLength(head); i++)
{
ListGet(head, i, &x);
printf("%d ", x);
}
printf("\n");
printf("请输入你要插入的数字\n");
scanf_s("%d", &s1);/*Visual stdio 2017写的代码,用scanf会报错,所有我用了scanf_s*/
ListInsert(head, s1);
printf("插入后的链表\n");
for (i = 0; i < ListLength(head); i++)
{
ListGet(head, i, &x);
printf("%d ",x);
}
printf("\n");
printf("请输入你要删除的数字\n");
scanf_s("%d", &s2);
/*while (ListDelete(head, s2) == 0)
{
printf("删除有误,请重新输入\n");
scanf_s("%d", &s2);
}*//*写法1,这里我是知道了原来同一个变量可以多次从键盘输入,之前没用过,想保留下来,各位神不用理这句*/
while (ListDelete(head, s2) == 0)
{
printf("链表中没有要删除的数字\n");
break;
}
/*if (ListDelete(head, s2) == 1)*//*不知道为什么要是保留这一句编译可以过去,但是程序输出了上一句printf就崩了,现在还没想明白*/
printf("目前链表数据\n");
for (i = 0; i < ListLength(head); i++)
{
ListGet(head, i, &x);
printf("%d ", x);
}
printf("\n");
ListDestroy(&head);
printf("链表销毁成功");
return 0;
}
求解一
我插入10,然后删除11;应该出现语句链表中没有要删除的数字,但是我的程序就崩了;
求解二
如果用if语句,就是这里,变一下
/*if (ListDelete(head, s2) == 1)*//*不知道为什么要是保留这一句编译可以过去,但是程序输出了上一句printf就崩了,现在还没想明白*/
printf("目前链表数据\n");
for (i = 0; i < ListLength(head); i++)
{
ListGet(head, i, &x);
printf("%d ", x);
,变成
if (ListDelete(head, s2) == 1)
{
printf("目前链表数据\n");
for (i = 0; i < ListLength(head); i++)
{
ListGet(head, i, &x);
printf("%d ", x);
}
为什么程序又会崩,难道是链表头文件那边的问题,求指导