将链表转换为数组(伪代码)

时间:2015-08-11 00:03:21

标签: arrays linked-list pseudocode

我正在研究算法,并且练习要求我将链表转换为数组(使用伪代码),这就是我所做的:

convert_LL_array (List, array)
  i = 0
  current = List.start

  while (current != null)    
      array[i] = current->data
      current = current->next
      i++

  return array

以下是答案:

convert_LL_array (List, array)
  i = 0
  current = List.start

  while (current->next != null)    
      array[i] = current->data
      current = current->next
      i++

  return array

当我与“null”比较时,为什么要使用“current-> next”?我认为这不会将最后一个元素添加到数组中。

1 个答案:

答案 0 :(得分:1)

你的伪代码似乎是正确的,没有任何问题。正如Tim指出,如果链表中只有一个元素,其他答案将不起作用。我只想补充一点,你可以查看如果您仍然有任何混淆,请在下面的链接上填写完整的代码。 https://ideone.com/qN1HBZ

struct ListNode{
    int data;
    struct ListNode* next;
    ListNode(int val):data(val),next(NULL){}
};

void convertLLtoArray(ListNode* head, vector<int>&arr){
    //if there is no element then return
    if(head==NULL)return;
    //crawling pointer
    ListNode* crawl = head;
    //iterate until list pointer become NULL
    while(crawl!=NULL){
        arr.push_back(crawl->data);
        crawl = crawl->next;
    }
    return;
}
相关问题