2016-05-08 98 views
-1

經過一定數量的步驟後,加載的(特定的)元素應該在執行/運行時被自己刪除(自動)。我想預先定義它,以便它可以執行自動-deletion在雙向鏈表雙向鏈接列表中的自動刪除元素

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先生我在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)