只是做了一些编辑,我尝试了你所说的,但它不起作用,所以我尝试了一些我更熟悉的东西,但它似乎无法正常工作。它奇怪地打印信息然后崩溃。例如:
当我输入 9-8-7-6-5-4-3-2-1 然后输入 0 进行打印时,它会打印回给我 0-0-0-9-1-2-3-4-5-6- 7-8 然后就崩溃了?
当我输入 1-2-3-4-5-6-7-8-9 然后输入 0 进行打印时,它会打印回给我 0-0-0-1-2-3-4-5-6-7- 8-9 然后崩溃。
#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 freeList(struct listNode *Head, int x);
//main
int main(){
struct listNode Head = {0, NULL};
int x = 1;
int ret = 0;
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);
}
ret = printList(&Head);
}
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;
}
}
int printList(struct listNode * Head){
struct listNode *current = Head;
while (Head != NULL){
printf("%d \n", *current);
current = current->next;
}
}
我建议创建一个从第一个节点开始并转到下一个节点直到下一个节点为空的迭代器,并建议使用类似的 next 而不是列表末尾(或有 next)。
然后打印你简单地继续通过迭代器并打印出值。
要插入,您从头项开始,迭代并比较值。
添加了一些伪代码,因为我并不是真正的 C++ 程序员。
class iterator
{
//provide a construction method for this
listNode current = Head;
listNode getValue()
{
return current;
}
void next()
{
//probably want to include some checks for validity here
current = current->next;
}
boolean hasNext()
{
return current->next != null;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)