【问题标题】:Array to List in C (iteratively)在 C 中列出的数组(迭代)
【发布时间】:2016-04-07 16:52:02
【问题描述】:

使用类型定义:

typedef struct Node *List;

typedef struct Node {
    int item;
    List next;
} Node;

我找到的递归解决方案:

List arrayToList(int arr[],int n,int idx) {
    if (n==idx) return NULL;
    List list=malloc(sizeof(Node));
    list->next=arrayToList(arr,n,idx+1);
    list->item=arr[idx];
    return list;
}

更新:以下几乎是正确的,但我不知道为什么最后会打印一个零。

List newNode() {
    List li=malloc(sizeof(Node));
    return li;
}

List arrayToList(int arr[],int n) {
    List li=newNode();
    List li1=li; /*save the beginning of the list*/
    int i;
    for (i=0;i<n;i++) {
        li->item=arr[i];
        li->next=newNode();
        li=li->next;
    }
    li=NULL;
    return li1;
}


void printList(List li) {
    while (li!=NULL) {
        li=li->next;
    }
    printf("\n");
}


int main(int argc, char* argv[]) {
    int arr[]={4,1,2,3,4,7,4,5,6,8};
    List li=arrayToList(arr,10);
    printList(li);
    return 0;
}

我得到的输出是: 4 1 2 3 4 7 4 5 6 8 0 。

更新 2:将函数 printList 更改为这个可以给我正确的输出:

void printList(List li) {
    while (li->next!=NULL) {
        printf("%d ",li->item);
        li=li->next;
    }
    printf("\n");
}

但我想知道为什么我应该有li-&gt;next!=NULL 作为守卫?

【问题讨论】:

  • “我想知道”。分享你的想法。
  • 你应该有li-&gt;next != NULL,因为你列表中的最后一个元素将指向null。

标签: c linked-list iteration


【解决方案1】:

这样做:

typedef struct node {
  int data;
  struct node *next;
} Node;

请注意,您希望next 指向下一个节点,而不是列表。

Node* arrayToList(int arr[],int n,int idx) {
  if (n==idx) return NULL;

  Node* headOfList = (Node*) malloc(sizeof(Node));
  Node* tail = headOfList;

  int i = n;
  for(; i < idx; i++) {
    // Create node
    Node* node = (Node*) malloc(sizeof(Node));
    node->data = arr[i];
    node->next = NULL;

    // Link Node to current list
    tail->next = node;
    tail = node;
  }

  return headOfList;
}

这只是一个草稿(我没有用编译器尝试过),但想法就在那里。

【讨论】:

    【解决方案2】:

    初始化你的第一个元素:

    Node *head = (Node*) malloc(sizeof(Node));
    head->data = arr[0];
    

    您需要一个指针来跟踪您当前的位置:

    Node *curr = head;
    

    创建一个for循环:

    for(int i = 1; i < len; i++)
    {
    
    }
    

    然后为每个元素添加一个新节点并将指针向前移动。

    curr->next = (Node*) malloc(sizeof(Node));
    curr = curr->next;
    curr->data = arr[i];
    

    不要忘记将列表的最后一个元素设置为空! (这可能发生在 for 循环之外。)

    n->next = NULL;
    

    【讨论】:

    • 似乎在列表中添加了一个额外的节点。看看更新。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-27
    • 1970-01-01
    • 1970-01-01
    • 2019-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多