|
完整例子:
- /* HELLO.C -- Hello, world */
- #include "stdio.h"
- #include "conio.h"
- typedef struct list{
- int value;
- struct list * next;
- }TList;
- int delPreByVal(int value);
- TList * setRandomValue(int account);
- void showAll();
- TList * head;
- main()
- {
- int v;
- head = setRandomValue(10);
- printf("Befor del:");
- showAll();
- printf("Enter the value:");
- scanf("%d",&v);
- delPreByVal(v);
- printf("After del:");
- showAll();
- getch();
- }
- /*建立链表*/
- TList * setRandomValue(int j){
- int tmp;
- TList *head=(TList *)malloc(sizeof(struct list));
- TList *ptr=head;
- if(j<1)return NULL;
- do{
- srand(j);
- tmp=rand();
- ptr->value=tmp;
- ptr->next=(TList *)malloc(sizeof(struct list));
- ptr=ptr->next;
- ptr->next=NULL;
- }while(j--);
- return head;
- }
- int delPreByVal(int v){
- /*特殊情况为要删的是头元素时*/
- TList *tmp,*ptr;
- printf("Enter del function!");
- ptr=head;
- tmp=ptr;
- while(ptr->next!=NULL){
- if(ptr->next->value==v){
- if(head->next==ptr){
- head=ptr->next;
- break;
- }else{
- tmp->next=ptr->next;
- free(ptr);
- break;
- }
- }
- tmp=ptr;
- ptr=ptr->next;
- }
- }
- void showAll(){
- TList *tmp=head->next;
- while(tmp!=NULL){
- printf("%d ",tmp->value);
- tmp=tmp->next;
- }
- }
复制代码
在WIN TC 下测试通过 |
|