DarlingLLO 2016-10-25 04:52 采纳率: 0%
浏览 855

关于链表的持续插入,求帮忙解决

List.cpp文件

List::List() {//初始化
head= NULL;
}
Node List::creatList() {//创建链表
head = (Node
)malloc(sizeof(struct Node));
Node*p1 = (Node*)malloc(sizeof(Node));
if (p1 == NULL) {
cout << "申请内存失败" << endl;
exit(0);
}
memset(p1, 0, sizeof(Node));
cout << "输入城市名称: ";
scanf_s("%s", p1->cityName, 20);
cout << "输入城市X坐标: ";
scanf_s("%d", &p1->x);
cout << "输入城市Y坐标: ";
scanf_s("%d", &p1->y);
head->Next = p1;
p1->Next = NULL;
cout << "creatList函数执行,链表创建成功" << endl;
return head;
}
void List::printList(Node*newList) {//遍历链表并打印到屏幕上
head = newList;
if (head == NULL) {
cout << "链表为空" << endl;
}
else {
head = head->Next;
while (head!= NULL) {
printf("%s (%d,%d)\n",head->cityName, head->x, head->y);
head = head->Next;
}
cout << endl;
}
}
Node*List::Insert(Node*pIn)//插入函数,每次都在头结点的下一个节点插入
{
pIn = (Node*)malloc((sizeof(Node)));
if (pIn == NULL) {
cout << "申请内存失败" << endl;
exit(0);
}
memset(pIn, 0, sizeof(Node));
cout << "输入城市名称: ";
scanf_s("%s", pIn->cityName, 20);
cout << "输入城市X坐标: ";
scanf_s("%d", &pIn->x);
cout << "输入城市Y坐标: ";
scanf_s("%d", &pIn->y);
pIn->Next = head->Next;
head->Next= pIn;
cout << "城市表头插入成功" << endl;
return head;
}

以下是main函数

#include"iostream"
#include"LinkList.h"
using namespace std;
void displayMenu();
static int choice;
void main() {
Node*pNew = (Node*)malloc(sizeof(Node));
Node*pInsert = (Node*)malloc(sizeof(Node));
List pList ;
while (true) {
displayMenu();
cout << "请选择:" << endl;
cin >> choice;
switch (choice) {
case 1:
cout << "输入新增城市信息" << endl;
pNew=pList.creatList();
break;
case 2:
pList.printList(pNew);
break;
case 3:
pNew=pList.Insert(pInsert);
break;
case 4:
cout << "case 4";
//Delete(&pList);
break;
case 5:
pList.find();
break;
default:
break;
}
}
}
void displayMenu() {
cout << " 【 【城市链表】 】 " << endl;
cout << "---------------------------------------------------------------------------" << endl;
cout << " 1.创建城市链表" << endl;
cout << " 2.更新显示所有城市" << endl;
cout << " 3.插入城市" << endl;
cout << " 4.删除城市" << endl;
cout << " 5.查找城市返回坐标" << endl;
}

  • 写回答

2条回答 默认 最新

  • DarlingLLO 2016-10-25 04:58
    关注

    是调用了printList函数之后再插入就有问题了

    评论

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序