2016-05-08 9 views
-1

特定のステップ数の後、ロードされた(特定の)要素は実行時/実行時に自動的に削除されるべきです。二重リンクリスト内の削除二重リンクリスト内の要素の自動削除

void del_begin() 
{ 
    struct node *temp; 

if(start==NULL) 
     return; 
    else 
    { temp=start; 
     start=start->next; 
       start->prev=NULL; 
     printf("Unloaded Wagon =%s ",temp->num); 
     free(temp); 
    } 
+1

あなたの質問は何ですか? – MikeCAT

+0

コードはどこですか? – jboockmann

+0

@MikeCAT sir私はC言語で二重リンクされたリストでプロジェクトを実装しています。私はそれを事前定義する特定のステップ数の後に要素を自動的に削除したい(自動削除) – Nitin

答えて

1

次のコードは、各要素にライフタイム値を割り当てることができる二重リンクリストを実装しています。 insertを呼び出すと、生涯が1だけ減少します。ノードの寿命が0であれば、そのノードはリストから削除されます。寿命値が負のノードは無視されるため、リストから削除されることはありません。

#include <stdio.h> 
#include <stdlib.h> 

struct dll{ 
    struct node* head; 
}; 

struct node { 
    struct node* next; 
    struct node* prev; 
    int value; 
    int lifetime; 

}; 

void insert(struct dll*, int, int); // insert a new node 
void step(struct dll*); // decrease the lifetime by one and remove "dead" nodes 
void print(struct dll*); // print the nodes and their lifetime 

int main(void) { 
    struct dll* dll = malloc(sizeof(struct dll)); 
    dll->head = NULL; 
    insert(dll, 1, -1); 
    insert(dll, 2, 5); 
    insert(dll, 3, 3); 
    insert(dll, 4, 0); 
    insert(dll, 5, 1); 
    print(dll); 
} 

void insert(struct dll* dll, int value, int lifetime) { 
    print(dll); 
    step(dll); 
    struct node* n = malloc(sizeof(struct node)); 
    n->value = value; 
    n->lifetime = lifetime; 
    if(dll->head == NULL) { 
     dll->head = n; 
     n->prev = dll->head; 
     n->next = dll->head; 
    } else { 
     n->prev = dll->head->prev; 
     dll->head->prev->next = n; 
     dll->head->prev = n; 
     n->next = dll->head; 
    } 
} 

void step(struct dll* dll) { 
    if(dll->head != NULL) { 
     struct node* n = dll->head; 
     do{ 
      if(n->lifetime == 0) { 
       // remove the node 
       struct node* next = n->next; 
       n->prev->next = n->next; 
       n->next->prev = n->prev; 
       free(n); 
       n = next; 
      } else if(n->lifetime > 0){ 
       // decrease lifetime by one 
       n->lifetime = n->lifetime - 1; 
       n = n->next; 
      } else { 
       n = n->next; 
      } 
     } while(n != dll->head); 
    } 
} 

void print(struct dll* dll) { 
    if(dll->head != NULL) { 
     struct node* n = dll->head; 
     do{ 
      printf("%d(%d) ", n->value, n->lifetime); 
      n = n->next; 
     } while(n != dll->head); 
    } 
    printf("\n"); 
} 

コードを実行時にプリントアウトされている次

1(-1) 
1(-1) 2(5) 
1(-1) 2(4) 3(3) 
1(-1) 2(3) 3(2) 4(0) 
1(-1) 2(2) 3(1) 5(1) 
関連する問題