打印有序的链表

时间:2012-11-05 21:03:20

标签: list linked-list sorted

刚刚对它进行了一些编辑,我尝试了你说的但它没有用,所以我尝试了一些我更熟悉的东西,但它似乎没有正常工作。它打印信息奇怪然后崩溃..例如: 当我输入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;
    }
}

2 个答案:

答案 0 :(得分:0)

我建议创建一个从第一个节点开始并进入下一个节点的迭代器,直到下一个节点为空,并建议使用类似下一个而不是列表结尾(或者下一个)。

然后打印简单继续通过迭代器并打印出值。 要插入头部项目并通过迭代器开始并比较值。

添加了一些伪代码,因为我不是真正的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;
    }
}

答案 1 :(得分:0)

int printList(struct listNode * Head){
struct listNode *current = Head;
while (Head != NULL){
      printf("%d \n", *current);
      current = current->next;
}

你非常接近。

看一下你的while循环中的条件 - 程序崩溃的原因是'Head'永远不会更新,所以条件总是正确的。所以程序只是将'current'设置为等于'current-&gt; next'而不停止直到你到达列表的末尾,此时'current-&gt; next'为NULL并且程序崩溃。

如果更改while循环以检查'current'是否为NULL而不是'Head',它将在到达列表末尾时停止,并且程序不会崩溃。

编辑:添加一些关于修复显示链表的额外零的指针。

struct listNode Head = {0, NULL};

在程序开始时,您将在链接列表中创建一个值为0的节点。因此,无论您的输入是什么,您总是至少有一个0。您可以考虑将Head初始化为NULL。如果这样做,则必须在insertNode函数中检查该条件。

你还得到一些额外的零,因为你正在检查你的循环条件('while(x&gt; 0)')之前你得到用来做出决定的输入( 'scanf(“%d”,&amp; x);')。您可能需要考虑使用'do ... while'而不是'while'来更改该顺序。通过示例查看http://www.cprogramming.com/tutorial/c/lesson3.html对'do ... while'的解释。

相关问题