问题描述
- 链表读取访问权限冲突
-
刚开始学链表,写了一个非递减单链表,先po程序吧#include<iostream> using namespace std; struct List //构建构建新节点的结构体 //非递减顺序排列 { int data; List * next; }; void insert(List * & headnode, int num) { List *s, *p = headnode, *q; //*s用于建立新节点 *p用于跟踪最新结点 //以下三行为构建新结点 s = new List; s->data = num; s->next = NULL; //以下if语句用于插入第一个结点 if (p->next == NULL) { headnode->next = s; p = s; return; } //新节点数据最小时的操作 if (headnode->next->data > s->data) { s->next = headnode->next; headnode->next = s; return; } //常规对比插入排序 for (q = headnode->next, p = headnode->next->next; p; q = p, p = p->next) { if (p->data >= s->data) { s->next = p; q->next = s; return; } } q->next = s; return; } void ShowList(const List * headnode) { cout << "您所输入的数为:"; while (headnode) { cout << headnode->data << 't'; headnode = headnode->next; } cout << endl; } int main() { int k = 0, m = 0; //k用于输入新数据 m用于计算节点数 List * headnode = NULL; cout << "请输入除零以外的任何数" << endl; cin >> k; while (k != 0) { insert(headnode, k); cin >> k; m++; headnode->data = m; } ShowList(headnode); //输出链表 }
# 先在此谢过大神了!~
解决方案
insert函数里有点问题,帮楼主改掉了,现在应该没错了,链表既然是没有头结点的,就没有必要从->next开始
#include<iostream>
using namespace std;
struct List
//构建构建新节点的结构体
//非递减顺序排列
{
int data;
List * next;
};
void insert(List * & headnode, int num)
{
List *s, *p = headnode, *q; //*s用于建立新节点 *p用于跟踪最新结点
//以下三行为构建新结点
s = new List;
s->data = num;
s->next = NULL;
//以下if语句用于插入第一个结点
if (p == NULL)
{
headnode = s;
//p = s;
return;
}
//新节点数据最小时的操作
if (headnode->data > s->data)
{
s->next = headnode;
headnode = s;
return;
}
//常规对比插入排序
for (q = headnode, p = headnode->next; p; q = p, p = p->next)
{
if (p->data >= s->data)
{
s->next = p;
q->next = s;
return;
}
}
q->next = s;
return;
}
void ShowList(const List * headnode)
{
cout << "您所输入的数为:";
while (headnode)
{
cout << headnode->data << 't';
headnode = headnode->next;
}
cout << endl;
}
int main()
{
int k = 0, m = 0; //k用于输入新数据 m用于计算节点数
List * headnode = NULL;
cout << "请输入除零以外的任何数" << endl;
cin >> k;
while (k != 0)
{
insert(headnode, k);
cin >> k;
//m++;
//headnode->data = m;
}
ShowList(headnode); //输出链表
}
解决方案二:
List * headnode = NULL;
然后
insert(headnode, k);
此时headnode是null
*p = headnode
if (p->next == NULL)
显然p是null怎么访问next
时间: 2024-10-21 17:08:31