weixin_43363018
南城啊呀呀呀
2019-05-04 10:10

用C++创建单链表,运行到p->next=(*list)->next;时显示发生访问冲突

  • c++

图片说明
代码如下

#include<iostream>
using namespace std;
struct Node//创建单链表结构体
{
    int date;
    Node *next;
};
int list_headinsert(Node **list, int a[], int n);
int getlist(Node *list, int i);
int main()
{
    int *p, n;
    cout << "请输入n=";
    cin >> n;
    p = new int[n];
    for (int i = 0; i < n; i++)
    {
        cout << "请输入第" << i << "个元素=";
        cin >> p[i];
    }
    Node **list=new Node*;//创建一个空表;
    if (*list == NULL)
    {
        cout << "空间申请失败";
        return 0;
    }
    list_headinsert(list, p, n);
    for (int i = 1; i < n; i++)//按顺序导出数据元素;
        cout << getlist(*list, i) << ' ';
    return 1;
}
int list_headinsert(Node **list, int a[], int n)//头插法新建带头结点的单链表,并将数组元素导入
{
    Node *p = new Node;
    p->next = NULL;
    for (int i = n; i >1; i--)
    {
        Node*p = new Node;
        p->date = a[i];
        p->next = (*list)->next;
        (*list)->next = p;
    }
    return 1;
}
int getlist(Node *list, int i)//查找链表数据元素
{
    Node *p = list->next;
    int j = 0;
    if (p == NULL)
    {
        cout << "空表";
            return 0;
    }
    while (p&& j < i)
    {
        p = p->next;
        j++;
    }
    return p->date;
}
  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

2条回答