c - 问题在链表中的特定位置插入节点
问题描述
我对函数 insertnodespecific 有一些问题。当我运行这个程序时,我首先使用 insertNodeFirst() 函数,然后使用 insertNodeEnd() 函数。然后我运行 list listNode() 函数,一切都很好。但是,当我尝试使用 insertNodeSpecific 函数时,该节点要么被添加为链表中的最后一个,要么被添加到另一个位置。任何人都可以看到该功能有问题吗?我假设该函数看起来类似于 insertNodeEnd() 函数。
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
struct node {
int data;
int key;
struct node *next;
};
struct node *head = NULL;
void insertNodeFirst();
void insertNodeEnd();
void insertNodeSpecific();
void listNode();
int choice = 0;
int main()
{
while(true)
{
printf("Enter a choice:\n"
"1: Insert a node at the beginning of the list:\n"
"2: Insert a node at the end of the list:\n"
"3: Insert a node at a specific position in the list:\n"
"4: List nodes: \n"
"5: Exit: \n");
scanf("%d", &choice);
switch (choice){
case 1:
insertNodeFirst();
break;
case 2:
insertNodeEnd();
break;
case 3:
insertNodeSpecific();
break;
case 4:
listNode();
break;
case 5:
exit(0);
return 0;
default:
printf("Invalid choice! \n");
break;
}
}
return 0;
}
void insertNodeFirst()
{
int data;
int key;
printf("Type in a value: \n");
scanf("%d", &data);
struct node *link = (struct node*)malloc(sizeof(struct node));
link->key = key;
link->data = data;
link->next = head; // point to old first node
head = link; // point to new first node
}
void insertNodeEnd()
{
int data;
printf("Type in a value: \n");
scanf("%d", &data);
struct node *newNode, *temp;
newNode = (struct node*)malloc(sizeof(struct node));
if(newNode == NULL)
{
printf("Unable to allocate memory! \n");
}
else
{
newNode->data = data;
newNode->next = NULL;
temp = head;
}
while(temp != NULL && temp->next != NULL)
{
temp = temp->next;
}
temp->next = newNode; //inserted data
}
void insertNodeSpecific()
{
int data = 0;
int pos = 0;
int i;
printf("Type in a value: \n");
scanf("%d", &data);
printf("Enter a position: \n");
scanf("%d", &pos);
struct node *temp2, *insertnode;
insertnode = (struct node*)malloc(sizeof(struct node));
insertnode->next = NULL;
temp2 = head;
insertnode->data = data;
if(temp2 == NULL)
{
printf("Unable to allocate memory! \n");
}
while(pos--)
{
temp2 = temp2->next;
}
temp2->next = insertnode;
}
void listNode()
{
struct node *ptr = head;
printf("List of nodes are:\n");
while(ptr != NULL)
{
printf("\n%d\n", ptr->data);
ptr = ptr->next;
}
printf("\n");
}
解决方案
推荐阅读
- c# - GameProgramming,原型模式:如何将泛型类从 C++ 转换为 C#?
- javascript - 从我的网站播放存储在 Google Cloud Storage 上的大型 .mp4 视频
- raspberry-pi - 树莓派升级失败
- sql - 简单的数据库表设计结构
- javascript - JS 以百分比而不是数字运行数据计数
- javascript - Grid.js 响应式大尺寸表
- javascript - 如何在两个异步操作之间暂停?
- django - 无法访问远程 vps 上的 django 开发服务器
- java - 在输出前留下特定的间隙
- computer-vision - Pytorch 张量维数乘法