首页 文章

创建节点的链接列表

提问于
浏览
-3

我想编写一个main函数,它将创建节点的链接列表,除了下一个字段之外,每个节点都在两个字段中保存两个int值 . (在主类之外创建一个struct节点 . )第一个int是一个计数节点数量另一个int是从1开始的Fibonacci序列中的下一个数字 . 继续在列表中添加节点,直到新节点中第二个字段中的值超过第一个字段* 1000中的值 .

在添加每个节点时,将计数输出到一行 . (不要在链表中添加最后一个节点 . )它应该基本打印出来自第二个字段的值,每列5行 .

输出应该如下所示:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

1   1    2     3     5
8   13   21    34    55
89  144   233   377   610   
987 1597  2584  4181  6765
10946 17711

我知道如何制作struct节点,我知道斐波纳契码

#include <stdio.h>
#include <stdlib.h>

typedef struct node {
  int x;
  int y;
  struct node * next;
} node_t;

int main()
{
  int first = 0, second = 1, nxt, c;
  int num = 0;


    for ( c = 1 ; c < 23 ; c++ )
      {
    if ( c <= 1 )
      nxt = c;
    else
      {
        nxt = first + second;
        first = second;
        second = nxt;
      }
    printf("%d\n", nxt);

      }

  return 0;
}

基本上需要有关节点部分的帮助 .

非常感谢任何帮助或指导 .

1 回答

  • 1

    创建节点

    应使用动态内存分配(malloc)创建单个节点,请参阅create_node()

    链接列表创建

    需要一个指向第一个项目的指针,另一个指向curr_item的指针 . 第一项必须存储到first_node中 . 创建每个项目后,必须将其附加到当前项目 . 必须更新curr_node以指向最后一项 . 以下代码说明了创建示例链接列表 .

    node_t *create_node(int nr, int fib );
    int main()
    {    
          node_t *first_node=NULL; /* First node */
          node_t *curr_node=NULL;  /* Current node */
          node_t *tmp_node=NULL;
          /* Creating a list of 20 items*/
          for(i=0;i<20;i++){
            if (first_node==NULL){
              curr_node=create_node(i,i*10);
              first_node=curr_node;
            }
            else{
              curr_node->next=create_node(i,i*10); /*appending to current */
              curr_node = curr_node->next;         /* make it as current */
            }
          }
          i=0;
          /* Traversing Linked list */
          for(tmp_node=first_node;tmp_node!=NULL;tmp_node=tmp_node->next){
             printf("%d --- %d\n",tmp_node->x, tmp_node->y);
             i++;
          }
        }
        node_t *create_node(int nr, int fib ){
            node_t *node;
            node = (node_t*) malloc(sizeof(node_t));
            node->x=nr;
            node->y=fib;
            node->next=NULL;
            return node;    
    
          }
    

    互联网上有很好的资源,谷歌搜索“c链表实现”

相关问题