簡體   English   中英

努力將整數轉換為鏈表。 不確定我在這里做錯了什么

[英]Struggling to convert an integer into a linked list. Not sure what I'm doing wrong here

下面的代碼應該接受一個整數(即分子)並將其轉換為一個鏈表,從最后開始。 例如,對於整數 603,我想創建 3->0->6。 但是出於某種原因,我的輸出只給了我 0->6,而完全忽略了 3? 我查看了我的代碼,但似乎看不出我的邏輯哪里出錯了。

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

    int numerator = sum1 + sum2;

    ListNode * ptr;

    while (numerator != 0) {

        int val = numerator % 10;
        numerator = numerator / 10;

        ListNode * node = new ListNode(val);

        // If list is empty, add node.
        if (!ptr) {
            ptr = node;
        // If list is not empty, traverse to end of list and then append.
        } else {

            while (ptr->next) {
                ptr = ptr->next;
            }
            ptr->next = node;
        }
   }

您的代碼丟失了列表的頭部,因為它存儲在ptr ,每次插入都會更改。

您可以以更有效的方式將節點附加到單向鏈表:

ListNode* head = 0;
ListNode** tail = &head;

// ...    

// Append the new node to the tail of the list.
ListNode* node = new ListNode(val);
*tail = node;
tail = &node->next;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM