C Simple LinkedList

时间:2016-03-30 07:43:00

标签: c

我在网上看了很多不同的问题,无法弄清楚我做错了什么。我现在可能走向错误的方向,因为我尝试了很多不同的事情。

我只是想在C中创建一个简单的单链接列表。我似乎无法弄清楚如何使列表保持连接。

我的节点的结构

typedef struct node
{
  double x;            // x-coordinate of this point in the tour
  double y;            // y-coordinate of this point in the tour
  struct node* next;   // Pointer to the next node in the linked list
} Node;

这是我制作列表的代码,我在main

中构造一个空节点first = NULL
Node* addFront(Node* first, double x, double y) {   

     first = malloc(sizeof(Node));
     if (first == NULL) {
        first->x = x;
        first->y = y;
        first->next = NULL;
     }
     else {
        Node * temp = malloc(sizeof(Node));
        temp->x = x;        
        temp->y = y;                      
        temp->next = first;                 
        first = temp;     
     }
     //Temp testing
     int size = 0;
     Node * current = first;
     while (current->next != NULL) {
        printf("(%.4f, %.4f)\n", current->x, current->y);
        current = current -> next;
        size++;
     }
     printf("Size: %d\n", size);

  return first;
}

一些注意事项:

检查first is是否为null应该是不必要的......应该只使用else语句构建列表。 (我的想法)

添加if / else语句后,我得到了一个似乎是无限循环的C,只是指向随机内存,最终导致分段错误。

我只是不知道还有什么要转向。非常感谢你的进步!

2 个答案:

答案 0 :(得分:4)

这个块完全没有意义:

 first = malloc(sizeof(Node));
 if (first == NULL) {
    first->x = x;
    first->y = y;
    first->next = NULL;
 }

可能你想在块内移动first = malloc(sizeof(Node));。它会工作,但它完全没必要,因为它在逻辑上等于else块。所以你可以在那里留下第二块:

    Node * temp = malloc(sizeof(Node));
    temp->x = x;        
    temp->y = y;                      
    temp->next = first;                 
    first = temp;
    return first;
    // or rather return temp directly

还有一点 - 您应该在malloc内存不足的情况下添加错误处理,因此您应检查temp == NULL并采取相应措施(从函数返回NULL或其他任何内容...)。

答案 1 :(得分:0)

对于初学者来说,即使是函数的第一个语句也是错误的,因为参数import subprocess """ continuously print command output and append it to file while running """ def run(command): popen = subprocess.Popen(command, stdout=subprocess.PIPE) return iter(popen.stdout.readline, b"") filename = "subprocess_output" f = open(filename, "a") for line in run(["/bin/bash", "infinite_loop.sh"]): print(line), # the comma keeps python from adding an empty line f.write(line) f.close() 的值被覆盖了。

first

该功能可以按以下方式查看

Node* addFront(Node* first, double x, double y) {   

     first = malloc(sizeof(Node));
     //...

或使用测试代码

Node * addFront( Node *first, double x, double y ) 
{   
    Node *temp = malloc( sizeof( Node ) );

    if ( temp != NULL )
    {
        temp->x = x;        
        temp->y = y;                      
        temp->next = first;                 

        first = temp;
    }

    return first;
}
相关问题