我在C编程中有关于链接列表的问题。 我写了这段代码,但在尝试运行代码时遇到了运行时错误。 我是C编程的新手,请帮助。
以下是我尝试处理的问题。我无法按字母顺序打印出来。
我正在做的问题是
a) Create a pointer to the start of the list called startPtr. The list is empty.
b) Create a new node of type GradeNode that’s pointed to by pointer newPtr of type GradeNodePtr.
Assign the string "Jones" to member lastName and the value 91.5 to member
grade (use strcpy). Provide any necessary declarations and statements.
c) Assume that the list pointed to by startPtr currently consists of 2 nodes—one containing
"Jones" and one containing "Smith". The nodes are in alphabetical order. Provide
the statements necessary to insert in order nodes containing the following data for
lastName and grade:
"Adams" 85.0
"Thompson" 73.5
"Pritchard" 66.5
这是代码:
#include <stdio.h>
#include <string.h>
int main(){
struct gradeNode{
char lastName [20];
double grade;
struct gradeNode *nextPtr;
};
typedef struct gradeNode GradeNode;
typedef GradeNode *GradeNodePtr;
GradeNodePtr startPtr = NULL;
GradeNodePtr currentPtr = NULL;
GradeNodePtr previousPtr = NULL;
GradeNodePtr newPtr;
if (newPtr != NULL){
newPtr = malloc(sizeof(GradeNode));
strcpy(newPtr -> lastName,"Jones");
newPtr -> grade = 91.5;
newPtr -> nextPtr = NULL;
}
//Insert "Adams"
//previousPtr is NULL, and currentPtr points to the first node in the list.
newPtr -> nextPtr = currentPtr;
startPtr = newPtr;
newPtr = malloc(sizeof(GradeNode));
strcpy(newPtr -> lastName,"Smith");
newPtr -> grade = 40.5;
newPtr -> nextPtr = NULL;
newPtr -> nextPtr = currentPtr;
startPtr = newPtr;
newPtr = malloc(sizeof(GradeNode));
strcpy(newPtr -> lastName,"Adams");
newPtr -> grade = 85.0;
//Insert "Thompson"
//previousPtr points to the last node in the list(containing Smith") and currentPtr is NULL
newPtr -> nextPtr = currentPtr; //or newPtr -> nextPtr = NULL
previousPtr -> nextPtr = newPtr;
newPtr = malloc(sizeof(GradeNode));
strcpy(newPtr -> lastName,"Thompson");
newPtr -> grade = 73.5;
//Insert "Pritchard"
//previousPtr points to the node containing "Jones" and currentPtr points to the node contaiing "Smith"
newPtr -> nextPtr = currentPtr;
previousPtr -> nextPtr = newPtr;
newPtr = malloc(sizeof(GradeNode));
strcpy(newPtr -> lastName,"Pritchard");
newPtr -> grade = 66.5;
currentPtr = startPtr;
while(currentPtr!=NULL){
printf("Lastname = %s\nGrade = %.1f\n\n",currentPtr->lastName,currentPtr->grade);
currentPtr = currentPtr->nextPtr;
}
}
答案 0 :(得分:1)
首先,你应该明确你的逻辑。
这里有一些你可以使用的提示。
stdlib.h
,其中包含malloc
的定义。在这种情况下,编译器将发出一条警告消息newPtr
后,您正在检查NULL
。它最初将是NULL
或一些垃圾值。只有在NULL
不正确的时候才会分配内存