2016-11-27 3 views
-1

リンクリストとして実装されているスタックの最初の3要素をロールしようとしています。たとえば、スタックが次のようになっていたとします。1 2 3 4 5ロール関数の後には次のようになります:3 1 2 4 5. 3番目の項目はスタックの先頭に移動し、それ以外はすべてスタックの1つ下の位置にシフトされます。ここで私は、ロール機能のために演奏されているされているもの:リンクリストを使用して構築されたスタック内の項目を移動するCプログラム

// roll function rolls the top 3 numbers on the stack 
struct item *roll(struct item *top){ 
     struct item *cur = top; 
     struct item *prev = NULL; 
     int i = 0; 
     // get cur and prev to point to proper positions in linked list 
     for(i = 0; i < 3; i++){ 
       prev = cur; 
       cur = cur->next; 
     } 
     // roll the linked list 
     prev->next = cur->next; 
     cur->next = top; 
     top = cur; 

     return top; 
} 
+1

あなたのコードに問題は何ですか? – Sniper

+1

質問をするのを忘れました。 –

+0

私はそれを実行すると正しく動作しません。結果は同じ順序でリンクされたリストですが、最後の項目が欠落しています。私はどこが間違っているかもしれないかについてのいくつかの指針を欲しいです。 – derek

答えて

0

あなたのループを実行する必要があるのn-1回

struct item *roll(struct item *top){ 
    struct item *cur = top; 
    struct item *prev = NULL; 
    int i = 0; 
    // get cur and prev to point to proper positions in linked list 
    for(i = 0; i < 2; i++){ 
      prev = cur; 
      cur = cur->next; 
    } 
    // roll the linked list 
    prev->next = cur->next; 
    cur->next = top; 
    top = cur; 

    return top; 
} 
void print() 
{ 
struct item *temp = roll(top); 
    while(temp!=NULL) 
    { 
    cout<<temp->value; 
    temp=temp->next; 
    } 
} 

出力

31245 
+0

理由はわかりませんが、この変更で、私のコードでは以前と同じ問題が発生しています – derek

+1

作成中または印刷中に間違いを犯しました。コード全体をアップロードします。 – Sniper

関連する問題