c - 为什么insertBeg没有在开头插入节点
问题描述
我正在尝试insertBeg
在开始时使用插入节点,但我无法正确
#include <stdlib.h>
#include <stdio.h>
struct node {
int data;
struct node *next;
}*init;
int length(struct node *n);
struct node *searchVal(struct node *n, int val);
struct node *createLinkedList(int data);
struct node *insertEnd(struct node *n, int data);
struct node *insertBeg( struct node *n, int data);
void printList(struct node *n);
int main(int argc, char **argv) {
init = createLinkedList(1);
insertEnd(init, 6);
insertBeg(init, 9);
printList(init);
}
void printList(struct node *n) {
if (n != NULL) {
while (n->next != NULL) {
n = n->next;
printf("%d", n->data);
}
} else {
printf("Empty List");
}
}
/**
* returns length of node
*/
int length(struct node *n) {
int count = 0;
if (!n) {
return 0;
}
struct node *ptr = n;
while(ptr != NULL) {
count = count + 1;
ptr = ptr->next;
}
return count;
}
struct node *searchVal(struct node *n, int val) {
struct node *pos;
if (!n) {
return NULL;
}
struct node *ptr = n;
while (ptr != NULL) {
if (val == ptr->data){
pos = ptr;
return pos;
} else {
ptr = ptr->next;
}
}
return NULL;
}
struct node *createLinkedList(int data) {
struct node *new_node;
new_node = (struct node *)malloc(sizeof(struct node));
if (new_node == NULL) return NULL;
new_node->data = data;
new_node->next = NULL;
return new_node;
}
struct node *insertBeg(struct node *n, int data) {
struct node *new_node;
new_node = (struct node *)malloc(sizeof(struct node));
if (new_node == NULL) {
return NULL;
}
new_node->data = data;
new_node->next = n;
n = new_node;
return n;
}
struct node *insertEnd(struct node *n, int data){
struct node *new_node, *temp;
new_node = (struct node *)malloc(sizeof(struct node));
if (new_node == NULL) {
return NULL;
}
new_node->data = data;
if (n == NULL) {
new_node->next = NULL;
temp = new_node;
} else {
temp = n;
while (temp->next != NULL) {
temp = temp->next;
temp->next = temp;
}
temp->next = new_node;
new_node->next = NULL;
}
return temp;
}
解决方案
insertBeg 返回一个节点,它应该是列表的新标头,您必须接受该返回类型并将其设置为新标头,如下所示:
int main(int argc, char **argv) {
struct node * newHeader;
init = createLinkedList(1);
insertEnd(init, 6);
newHeader = insertBeg(init, 9);
init = newHeader;
printList(init);
}
您还需要按如下方式编辑打印功能,因为您错过了那里的几个节点:
void printList(struct node *n) {
if (n != NULL) {
while (n != NULL) {
printf("%d", n->data);
n = n->next;
}
} else {
printf("Empty List");
}
}
您可以在此处查看完整代码以供参考:https ://ideone.com/WX9TKF
推荐阅读
- concourse - 将构建目录 (/dist) 从一个作业传递到大厅中的下一个作业
- python - 请求通过字典中的每一行:如何修复
- python - 如何创建已定义的结构化元数据以供使用?
- css - Highchart极坐标,左对齐x标签 - 中断标签距离
- c# - 正则表达式以两个字母字符开头,然后是任何数字
- json - 通过 Shell 脚本读取 JSON 文件并替换密钥
- python - 如何在 python 中创建和销毁变量?
- kubernetes - Kubernetes kubectl apply 命令不起作用,给出连接被拒绝错误
- ios - 类型 Any 没有成员计数,二维数组
- javascript - 数组过滤器没有返回正确的零?