嗨,这是我关于堆栈溢出的第一个问题。我是一名软件工程专业的学生,我才刚刚开始理解链表。我目前只是在玩耍以更好地了解链表,所以请对我轻松一点。这应该是一个基本概念,但对我来说有点挑战。有谁可以向我解释为什么printList函数不能为我遍历列表。我已经看到了一些可行的示例,但我真的很想了解为什么我的逻辑不适用于此功能。
我的代码在下面,我正在使用gcc编译我的代码,不确定是否会有所不同
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
struct node{
int data;
struct node* next;
}node;
void printList(struct node *head){
struct node *temp = head;
while(temp->next != NULL){
printf("Here\n");
printf("%d - ",temp->data);
temp = temp->next;
}
printf("\n");
}
//this will create a new node and return a new created node
//data will be set to zero
//next pointer is set to null
struct node createNode(){
struct node temp;
temp.data = 0;
temp.next = NULL;
return temp;
}
//this will add a node to the beginning of the list
//you will need to pass a new head and pass the data you want stored of type int
//this will return a type node
struct node addNode(struct node head,int data){
struct node temp;
struct node ptr;
temp = createNode();
temp.data = data;
if(head.next == NULL){//whent the list is empty
head = temp;
}else{
ptr = head;
while(ptr.next !=NULL){
ptr = *ptr.next;//this will traverse the list until it reaches the end
}
ptr.next = NULL;
head.next = ptr.next;
}
printf("Added: %d\n",temp.data);
return head;
}
int main(){
struct node head = createNode();
struct node *temp = &head;
int userNum;
while(userNum != -1){
printf("Enter a number to add to the linked list: ");
scanf("%d",&userNum);
if(userNum == -1){//this will end the loop
break;
}else{
addNode(*temp,userNum);
}
}
printList(temp);
return 0;
}
我的addNode函数起作用,但是我不明白为什么对于printList()什么都不会打印出来。如果有任何区别,我正在使用gcc作为编译器。
我认为您的addNode和createNode函数存在一些问题。要访问指向struct属性的指针,必须使用'->'。并且您必须使用“。”当您处理普通结构(而不是指针)时。您可以将malloc用于createNode函数,因为您将处理一个应用了某些指针的链表。在addNode函数中,因为要处理指向struct的指针,所以可以在参数中使用* head而不是head,并且可以将temp和ptr更改为* temp和* ptr。