C語言單鏈表的建立,插入,刪除,逆致

` /************************************************************************* > File Name: link.c > Author: 胡若晨 > Mail: ----------------------------- > Created Time: 2016年03月29日 星期二 14時01分11秒 ************************************************************************/ #include<stdio.h> #include<stdlib.h>指針

struct Node { int data; struct Node *next; };code

struct Node *create() //建立鏈表 { struct Node *p,*q,*head; //q是前驅指針 char interrupt[10]; //終端符element

p = q = head = (struct Node *) malloc (sizeof(struct Node));

printf("please input data:");
scanf("%d",&p->data);

// printf("interrupt? yes($),no(any key) : "); // scanf("%s",interrupt); // while(p->data != interrupt[0]){ while(p->data != 0){ q = p; p = (struct Node *) malloc (sizeof(struct Node));input

printf("please input data:");
    scanf("%d",&p->data);

// printf("interrupt? yes($),no(any key) : "); // scanf("%s",interrupt);io

q->next = p; //鏈接鏈表
}

p->next = NULL;

return head;

}終端

void print(struct Node *head) { while(head != NULL){ printf("%4d",head->data); head = head->next; } printf("\n");bug

}im

struct Node *delete(struct Node *head) { struct Node *p,*q;//q是前驅指針 p = q = head; int del,d; printf("\nplease input the del:"); scanf("%d",&del);鏈表

q = p = head;

while(p){
    d = del;
    if( p->data != d){
        q = p;
        p = p->next;
    }
    else 
        break;
    if(!p){
        printf("can't find\n");
    }
}
if(p == head){
    head = head->next;
}
else{
    q->next = p->next;
}

return head;
free(p);

}next

struct Node *insert(struct Node *head) { struct Node *p,*ins; int e,inst;

printf("\nplease input the address(after) you want to insert:");
scanf("%d",&inst);
printf("\nplease input the element you want to insert:");
scanf("%d",&e);

p = (struct Node *) malloc (sizeof(struct Node));

p->data = e;

while(ins->data != inst){
    ins = ins->next;
}
if(ins->next == NULL){
    printf("can't find\n");
}
else{
    p->next = ins->next;
    ins->next = p;
}
if(head == NULL){
    head = p;
    p->next = NULL;
}

// else{ //insert after head // p->next = head->next; // head->next = p; // } // else{//insert before head // p->next = head; // head = p; // }

return head;

} struct Node *reverse(struct Node *head) { struct Node *p,*r;

if(head->next != NULL){
    p = head;
    r = p->next;
    p->next = NULL;//link tail == NULL
    printf("p->data = %d\n",p->data);

    while(r){
        p = r;
        r = r->next;
        p->next = head;
        head = p;
    }
}
printf("\nreverse success\n");
printf("The result is as following\n");

return head;

}

int main(void) { struct Node *head;

head = create();
print(head);

/下面這個地方必定要寫成head = delete(head);以刷新head,博主就是在這裏打成了delete(head);結果沒法刪除頭節點,找了好久的bug,找到以後。。。。。。。/ head = delete(head); print(head); head = insert(head); print(head); head = reverse(head); print(head);

return 0;

} `

相關文章
相關標籤/搜索