` /************************************************************************* > 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; };
struct Node *create() //创建链表 { struct Node *p,*q,*head; //q是前驱指针 char interrupt[10]; //终端符
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));
printf("please input data:"); scanf("%d",&p->data);
// printf("interrupt? yes($),no(any key) : "); // scanf("%s",interrupt);
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");
}
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);
}
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;
} `