【发布时间】:2017-03-26 21:58:00
【问题描述】:
我正在尝试将一个新节点添加到链表的末尾,我可以添加一些内容,但是当我将其打印出来时,该节点的值为“0”。我认为这可能会发生,因为我可能忽略了在某处初始化变量,或者忘记分配内存所述变量。但我无法让它工作。
这是我的源代码:
我的链表/结构:
#include<stdio.h>
typedef char DATA;
struct Node {
DATA d;
struct Node *next;
};
我的 printList 函数:
void printList(struct Node **head) {
struct Node *newNode = malloc(sizeof(struct Node));
struct Node *temp;
temp = *head;
printf("Linked list:");
while (temp->next != NULL) {
printf( " \n %d ", temp->d);
temp = temp->next;
}
printf("\n");
}
我的 insertNodeAtEnd 到结束函数:
// inset data at end
void insertNodeAtEnd(struct Node *head) {
struct Node *newNode = malloc(sizeof(struct Node));
struct Node *currentNode, *temp;
temp = newNode;
currentNode = newNode;
printf("Enter a Node to insert at the end of the list \n");
scanf("%s", &newNode->d);
newNode->next = NULL;
if (head == NULL) {
head = newNode;
currentNode = newNode;
} else {
temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
还有我的 main():
int main() {
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
struct Node *head = newNode;
struct Node *temp = newNode;
head->d = 1;
int i = 0;
printf("Enter 3 numbers");
for (i = 0; i < 3; i++) {
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
scanf("%d", &temp->d);
temp->next = newNode;
temp = temp->next;
}
insertNodeAtEnd(head);
printList(&head);
return 0;
对不起,任何混乱的代码,我在这方面还是相当新的
【问题讨论】:
-
for (temp= *head; temp != NULL; temp = temp->next){ printf( "%d\n", temp->d); }:: for() 循环是你的朋友。 -
void insertNodeAtEnd(struct Node *head)而this是使用指针指向的地方;不在 print() 函数中。 -
%d和%s的scanf不匹配char(又名DATA)。如果要输入数字,应将typedef char DATA;更改为typedef int DATA;。然后进行匹配的输入输出。 -
修复this
标签: c linked-list