【发布时间】:2019-10-29 03:37:29
【问题描述】:
您好,这是我关于堆栈溢出的第一个问题。我是一名软件工程专业的学生,我刚刚开始了解链表。我目前只是为了更好地理解链表,所以请放轻松。这应该是一个基本概念,但对我来说理解起来有些困难。有没有人可以向我解释为什么 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 作为我的编译器。
【问题讨论】:
-
欢迎来到 StackOverflow - 这个问题已经被问过很多次了 - 我投票结束这个问题作为重复。请阅读help center 和How to Ask。
-
请注意,在您的 addNode 函数中,您会混淆一个不是名称为“ptr”的指针的变量的情况。我认为这不是一个好主意。
-
"->" 适用于指针是合法的。 “。”不是,如果你尝试它,编译器会拒绝它。 (是的,只要不是指针,您就可以将“.”应用于取消引用的指针。)
-
尝试研究 C 是按值传递的含义,然后回来仔细查看您的 addNode 函数。
标签: c