单链表某一元素的删除

来源:互联网 发布:淘宝分销商品怎么上架 编辑:程序博客网 时间:2024/05/17 01:47

为啥总是犯十分智障的错误!!!

错误代码:

#include <stdio.h>#include <stdlib.h>//删除元素 typedef struct LNode{    int data;    LNode *next;}*List,LNode;void Creat(List &L,int n){//创建链表   List p;//用于循环创建的节点    L=(List)malloc(sizeof(struct LNode));    L->next=NULL;    for(int i=1;i<=n;i++){        p=(List)malloc(sizeof(struct LNode));        scanf("%d",&p->data);        p->next =L->next;        L->next=p;    } }//创建成功void Delete(List &L,int e){    List L1,L2;//重新使用一个只用来改变链表结构的指针    L1=L->next;//首先移动     L2=L;     int flag=0;   while(flag!=1&&L1){    if(L1->data==e){       L1->next=L2->next;         free(L1);            flag=1;                 }        else{            L2=L2->next;            L1=L1->next;         }           }    if(flag==0)    printf("失败");    if(flag==1)    printf("成功");       }void Print(List L3){    L3=L3->next;     while(L3){              printf("%d",L3->data);        L3=L3->next;    }}int main (){    List L;    int n,e;    printf("请输入元素的个数以及删除的元素:");    scanf("%d,%d",&n,&e);    Creat(L,n);    Print(L);    Delete(L,e);   Print(L);    return 0;   } 

正确代码:

#include <stdio.h>#include <stdlib.h>//删除元素 typedef struct LNode{    int data;    LNode *next;}*List,LNode;void Creat(List &L,int n){//创建链表   List p;//用于循环创建的节点    L=(List)malloc(sizeof(struct LNode));    L->next=NULL;    for(int i=1;i<=n;i++){        p=(List)malloc(sizeof(struct LNode));        scanf("%d",&p->data);        p->next =L->next;        L->next=p;    } }//创建成功void Delete(List &L,int e){    List L1,L2;//重新使用一个只用来改变链表结构的指针    L1=L->next;//首先移动     L2=L;     int flag=0;   while(flag!=1&&L1){    if(L1->data==e){       L2->next=L1->next;         free(L1);            flag=1;                 }        else{            L2=L2->next;            L1=L1->next;         }           }    if(flag==0)    printf("失败");    if(flag==1)    printf("成功");       }void Print(List L3){    L3=L3->next;     while(L3){              printf("%d",L3->data);        L3=L3->next;    }}int main (){    List L;    int n,e;    printf("请输入元素的个数以及删除的元素:");    scanf("%d,%d",&n,&e);    Creat(L,n);    Print(L);    Delete(L,e);   Print(L);    return 0;   } 

错误原因:

L2->next=L1->next;  

还是眼高手低,以为像这种简单的没什么问题!!!

阅读全文
0 0
原创粉丝点击