如何修复我的分配程序与运行时错误

时间:2015-05-07 15:15:46

标签: c linked-list

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

struct listnode
{
    int data;
    struct listnode *nextptr;
    struct listnode *prevptr;
}*head,*tail;

void print_linked_list(){
    struct listnode *temp;
    temp=head;

    while(temp!=NULL){
        printf("%d ",temp->data);
        temp = temp->nextptr;
    }
}

void InsertAtHead(int x){
    struct listnode *var,*temp;
    var=(struct listnode *)malloc(sizeof(struct listnode));
    var->data=x;

    if(head==NULL){
        head = var;
        head->prevptr=NULL;
        head->nextptr=NULL;
        tail=head;
    }

    else{
        temp=var;
        temp->prevptr=NULL;
        temp->nextptr=head;
        head->prevptr=temp;
        head=temp;
    }
}

void InsertAtTail(int x) {
    struct listnode *var,*temp;
    var=(struct listnode *)malloc(sizeof(struct listnode));
    var->data=x;
    if(head==NULL){
        head=var;
        head->prevptr=NULL;
        head->nextptr=NULL;
        tail=head;
    }

    else{
        tail=head;
        while(tail!=NULL){
            temp=tail;
            tail=tail->nextptr;
        }

        tail=var;
        temp->nextptr=tail;
        tail->prevptr=temp;
        tail->nextptr=NULL;
    }
}

int DeleteAtHead(){
    struct listnode* temp;
    temp=head;

    if(temp->nextptr==NULL){
        free(temp);
        head=NULL;
        tail=NULL;
        return 0;
    }

    head=temp->nextptr;
    head->prevptr=NULL;
    free(temp);
    return 0;
}

int DeleteAtTail(){
    struct listnode* temp;
    temp=tail;

    if(temp->prevptr==NULL){
        free(temp);
        head=NULL;
        tail=NULL;
        return 0;
    }

    tail=temp->prevptr;
    tail->nextptr=NULL;
    free(temp);
    return 0;
}


int main(){

    head=NULL;

    char operation[10];
    char place[5];
    int element;

    /** write code here ^-^ya **/
    while(scanf("%s ",operation)!=EOF){

        if(strcmp(operation,"insert")==0){
            scanf("%s",place);
            if(strcmp(place,"head")==0){
                scanf("%d",&element);
                InsertAtHead(element);
            }

            else if(strcmp(place,"tail")==0){
                scanf("%d",&element);
                InsertAtTail(element);
            }
        }

        else if(strcmp(operation,"delete")==0){
            scanf("%s",place);
            if(strcmp(place,"head")==0){
                DeleteAtHead();
            }

            else if(strcmp(place,"tail")==0){
                DeleteAtTail();
            }
        } 
    }

    print_linked_list();

    printf ("\n");

    return 0;
}

当我提交代码时,它始终显示运行时错误(RE)和超出时间限制(TLE)。 我试着释放一些记忆但没用。我该如何解决这个问题?

0 个答案:

没有答案