Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
2.3 kB
2
Indexable
Never
#include <stdio.h>
#include <stdlib.h>
//#include "function.h"

void printList(Node *head){
    Node *temp;
    for(temp = head; temp!=NULL; temp=temp->next) {
        printf("%d ", temp->data);
    }
}

void freeList(Node *head){
    Node *temp;
    for(temp=head; temp!=NULL; temp=head){
        head = head->next;
        free(temp);
    }
}

int main()
{
    Node *head;
    int data;

    head = createList();

    while(1){
        scanf("%d", &data);
        if(data>-1){
            deleteNode(&head,data);
        }else break;

    }

    printList(head);
    freeList(head);
    return 0;
}

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

typedef struct _Node {
    int data;
    struct _Node *next;
} Node;

//上面是題目附的,下面是我朋友寫的

void deleteNode(Node ** nd, int data){
    Node* current=*nd;
    Node* previous=*nd;
    //case 1 無頭騎士
    if(*nd==NULL)   return;
    //case 2 上斷頭台
    else if(data==1){
        *nd=current->next;
        free(current);
        current=NULL;
    }//case 3 循線追殺
    else{
        while(data!=1){
            previous=current;
            current=current->next;
            data--;
        }
        previous->next=current->next;
        free(current);
        current=NULL;
    }
}

Node* createList(){
    Node* temp_head;
    Node* previous;
    Node* current;
    int in,count;
    while(1){
        scanf("%d",&in);
        if(in==-1)  break;
        
        count++;
        if(count==1){                   //只要做頭
            temp_head=(Node*)malloc(sizeof(Node));
            temp_head->data=in;
            temp_head->next=NULL;
        }else if(count==2){             //做出頭跟一個current
            current=(Node*)malloc(sizeof(Node));
            temp_head->next=current;
            current->data=in;
            current->next=NULL;
        }else{                          //用previous存前一個current,在做一個新的current
            previous=current;
            current=(Node*)malloc(sizeof(Node));
            previous->next=current;
            current->data=in;
            current->next=NULL;
        }
    }
    if(count==0)    temp_head=NULL;
    return temp_head;
}