我正在尝试使用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;
}
答案 0 :(得分:3)
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
答案 1 :(得分:0)
函数insertBeg是正确的,它会返回已标记为init的链表的新Initial Element。
因此代替
insertBeg(init, 9);
在您的主要功能中调用
init = insertBeg(init, 9);
这将解决您的问题。
除此之外,您的功能似乎还不错。