0

要件は、ユーザーの入力から作成されるリンク リストのルートにinputa を返す関数です。お気に入り:Node*input

Node *input()
{
     Node *root; //not yet allocated
     while(1)
     {    
           //take in numbers from the user and correspondingly add them 
           //to the linked list and quit when anything else is entered

           if(input character is a number)
           {
                //allocate memory to a fresh pointer and push the number to it
                //and add this new Node to the LL
           }
     }
     return root;
}

-> while ループ本体の前に、 メモリを事前に割り当てrootて最初の番号をプッシュする解決策があります。しかしここで、ユーザーが何も入力しない場合は、すぐに削除する必要があります。

->また、root が while ループで NULL かどうかを確認し、そうであれば、 memory を割り当てて、それが 1 回だけ発生するようにする方法もあります。

しかし、LL の根本から生じる奇妙な状況を解消する解決策があるかどうかを知りたいです。

->たぶん、値を保持しないダミーノードを最初に保持できます。

しかし、それとは別に?全体を行うためのより良い方法があれば、それを提案してください。

4

3 に答える 3

2

次のようなことができます:

struct Node* root = 0; // don't forget to initialize

while (...) {
  if (...) {
    struct Node * item = ... ;  // allocate
    item->data = ...;
    item->next = root;
    root = item;
  }
}

return root;

これで完了です。最初の要素に特別なケースは必要ありません。リストの終わりはヌルnextポインタで示されます。

毎回リスト全体をトラバースせずに、リストを挿入順に並べたい場合は、次のことができます。

struct Node* root = 0; // don't forget to initialize
struct Node* tail = 0;

while (...) {
  if (...) {
    struct Node * item = ... ;  // allocate
    item->data = ...;
    item->next = 0;

    if (tail)
      tail->next = item;
    tail = item;

    if (!root)
      root = item;
  }
}

return root;

特別なケースの割り当てはありませんが、特別なケースの割り当てです。

于 2012-09-23T13:48:15.170 に答える
1

これは、特殊なケースを回避するバージョンです。ポインターツーポインターを使用します。

struct list {
        struct list *next;
        int val;
        };

struct list *input(void)
{
struct list *ret=NULL, **tail;
char buff[100];

for (tail= &ret; fgets(buff, sizeof buff, stdin);       ) {
        int val;
        if ( sscanf(buff,"%d", &val) < 1) continue;
        *tail = malloc (sizeof **tail);
        (*tail)->next = NULL;
        (*tail)->val = val;
        tail = &(*tail)->next;
        }
return ret;
}
于 2012-09-23T15:38:52.360 に答える
1

どのソリューションも複雑に見えませんが、ダミー ノードを使用すると、非常にクリーンなコードが得られます。

Node root; //stored on the stack
root->next = NULL;

//...

return root->next;
于 2012-09-23T13:46:39.543 に答える