我正在做我的家庭作业,这就是我所得到的。我现在需要知道如何打印已经输入到列表中的信息。我还需要重新配置insertNode函数,以便对列表进行从小到大的排序。
#include <stdio.h>
#include <stdlib.h>
struct listNode{
int data; //ordered field
struct listNode *next;
};
//prototypes
void insertNode(struct listNode *Head, int x);
int printList(struct listNode *Head, int x);
int freeList(struct listNode *Header, int x);
//main
int main(){
struct listNode Head = {0, NULL};
int x = 1;
printf("This program will create an odered linked list of numbers greater"
" than 0 until the user inputs 0 or a negative number.\n");
while (x > 0){
printf("Please input a value to store into the list.\n");
scanf("%d", &x);
insertNode(&Head, x);
}
printf("Program terminated.\n");
system("PAUSE");
}
void insertNode(struct listNode * Head, int x){
struct listNode *newNode, *current;
newNode = malloc(sizeof(struct listNode));
newNode->data = x;
newNode->next = NULL;
current = Head;
while (current->next != NULL && current->data < x)
{
current = current->next;
}
if(current->next == NULL){
current->next = newNode;
}
else{
newNode->next = current->next;
current->next = newNode;
}
}发布于 2012-11-06 03:38:26
启动时Header->next为NULL,添加元素时将current更改为Header
current = Header;
write(current->next !=NULL);
// set current to be Header->next (which is NULL)
current = current->next;
// dereference null
current->next = newNode;相反,应将新元素添加到末尾:
current = Header;
while (current->next != NULL)
current = current->next;
current->next = newNode;发布于 2012-11-06 03:45:09
current = Header;
write(current->next !=NULL);
current = current->next;
current->next = newNode;您正在尝试访问current->next,但每个人都没有分配它。实际上,您并没有在链表中搜索正确的位置来插入它(从您的问题来看,它听起来应该是排序的)。
尝试如下所示:
current = Header;
while (current->next != NULL && current->data < x)
{
current = current->next;
}
if(current->next == NULL)
{
current->next = newNode;
}
else
{
newNode->next = current->next;
current->next = newNode;
}发布于 2012-11-06 03:46:41
在您的实施中有三个问题:
current= Header->next;//节点Header->next当前指向
Header->next=newNode;// let header->下一个指向新元素
newNode-> next =current;//让新的ele的下一个指向旧的顶部ele
if (header==0)
header=newNode
否则
//像用2. 写的一样
所有这些都可以用一种不同的方式来完成,但这是一个常见的列表问题……(嗯,不知何故,代码的4个前导空格不起作用?)
https://stackoverflow.com/questions/13239025
复制相似问题