q是nullptr 位置不同引发程序中断,可觉得这2个位置没什么不同,放到红线会出错,放到for就正常了
#include "pch.h"#include <stdio.h>
#include<malloc.h>
#include<stdlib.h>
typedef struct NODE {
int data;
struct NODE* pNext;
} NODE,*PNODE;
//函数声明
PNODE create_list(void);
void traverse_list(PNODE pHead);
bool is_empty(PNODE pHead);
int length_list(PNODE pHead);
bool insert_list(PNODE, int pos, int val); //在pHead所指向链表的第pos个节点的前面插入一个新的结点,该节点的值是val, 并且pos的值是从1开始
bool delete_list(PNODE, int, int *);
void sort_list(PNODE);
int main()
{
int val;//被删除节点数据域的值
PNODE pHEAD = NULL;
pHEAD = create_list();
traverse_list(pHEAD);
sort_list(pHEAD);
//delete_list(pHEAD, 2, &val);
//printf("被删除的节点的值为:%d\n", val);
traverse_list(pHEAD);
return 0;
}
PNODE create_list() {
int len;
int val;
PNODE pHEAD = (PNODE)malloc(sizeof(NODE)); //头指针,指向头节点
if (NULL == pHEAD) {
printf("内存创建失败,程序中断 ");
}
PNODE phai = pHEAD;
phai->pNext = NULL;
printf("请输入创建节点的个数:");
scanf_s("%d", &len);
for (int i = 0; i < len; i++)
{
printf("请输入第%d个节点的值:", i + 1);
scanf_s("%d", &val);
PNODE pNEW = (PNODE)malloc(sizeof(NODE));
if (NULL == pNEW) {
printf("内存创建失败,程序中断 ");
}
pNEW->data = val;
phai->pNext = pNEW;
pNEW->pNext = NULL;
phai = pNEW;
}
return pHEAD;
}
void traverse_list(PNODE pHead)
{
PNODE p = pHead->pNext;
while (NULL != p)
{
printf("%d ", p->data);
p = p->pNext;
}
printf("\n");
return;
}
int length_list(PNODE Phead) {
PNODE p = Phead->pNext;
int len=0;
while (NULL!=p)
{
len++;
p = p->pNext;
}
return len;
}
bool is_empty(PNODE pHead) {
PNODE p = pHead->pNext;
if (NULL == p)
return true;
else return false;
}
bool insert_list(PNODE Phead, int pos, int val) {
PNODE p;
p = (PNODE)malloc(sizeof(NODE));
p->data = val;
PNODE t;
PNODE q=Phead;
int i = 0;
while (q!=NULL&&i<pos-1)
{
q = q->pNext;
i++;
}
if (q == NULL || i > pos - 1) //注意为pos-1;
return false;
t=q->pNext;
q->pNext = p;
p->pNext = t;
return true;
}
bool delete_list(PNODE Phead, int pos, int *val) {
PNODE q = Phead;
int i = 0;
while (q->pNext!= NULL && i < pos - 1)
{
q = q->pNext;
i++;
}
if (q->pNext == NULL || i > pos - 1) //注意为pos-1;
return false;
*val = q->pNext->data;
PNODE p= q->pNext;
q->pNext = q->pNext->pNext;
free(p);
p = NULL;
return true;
}
void sort_list(PNODE Phead) {
int i, j, t;
int len = length_list(Phead);
PNODE p ;
PNODE q;
for (i = 0,p= Phead->pNext; i < len - 1; i++, p = p->pNext)
{
for (j = i + 1, q= p->pNext; j < len; j++, q = q->pNext)
{
if (p->data > q->data)
{
t = p->data;
p->data = q->data;
q->data = t;
}
}
}
return;
}