zoukankan      html  css  js  c++  java
  • 单链表的删除

    将表的第i个节点删去:

    1. 找到ai-1存储位置p
    2. 保存要删除的结点的值
    3. 另p->next指向ai的直接后继结点
    4. 释放结点的空间

    如图:

          

    代码:

    include<stdio.h>
    #include<stdlib.h>
    #define OK 1
    #define ERROR 0
    #define OVERFLOW 0
    typedef struct LNode{
            int data;
            struct LNode *next;
    }LNode,*LinkList;
    //建立一个只含头结点空链表
    int InitList_L(LinkList &L){
            L=(LinkList)malloc(sizeof(LNode));
            if(!L){
                    exit(OVERFLOW); // 存储分配失败
            }
            L->next=NULL;
            return OK;
    }

    //建立含n个元素的单链表,并且是尾插入,
    int CreateList_L(LinkList &L,int n){
            LinkList p,q;
            int i;
            printf("Input the datas:");
            q=L;
            for(i=0;i<n;i++){
                    p=(LinkList)malloc(sizeof(LNode));
                    scanf("%d",&p->data);
                    p->next=q->next;
                    q->next=p;
                    q=p;
            }
                    return OK;
    }

    //若表中存在第i个结点删除并用e带回其值
    int ListDelete_L(LinkList &L,int i,int &e){
            LinkList p,q;
            int j=0;
            p=L;
            while(p->next&&j<i-1){//查找第i个结点,若存在,p指向其直接前驱
                    p=p->next;
                    ++j;
            }
            while(!(p->next)||j>i-1){
                    return ERROR;
            }
            q=p->next;//q指向第i个结点
            p->next=q->next;
            e=q->data;
            free(q);
            return OK;
    }
    main(){
            int i,n,e;
            LinkList L;
            InitList_L(L);
            printf("Input the length of the list L:");
            scanf("%d",&n);
            CreateList_L(L,n);
            printf("Input the delete  location:");
            scanf("%d",&i);
            if(ListDelete_L(L,i,e)){
                    printf("Output the datas:");
                    TraverseList_L(L);
            }else{
                    printf("Can't find the delete data! ");
            }
            printf(" ");
    }
    结果:

    android@android-Latitude-E4300:~/work/c/danlianbiao$ ./listDelete
    Input the length of the list L:5
    Input the datas:1 3 5 7 9
    Input the delete  location:3
    Output the datas:1379

  • 相关阅读:
    互评Beta版本——可以低头,但没必要——取件帮
    作业要求 20181127-5 Beta发布用户使用报告
    从程序员到CTO的Java技术路线图
    feodora git command autocomplete
    java case
    哑铃 图解
    links
    编辑被标记为“只读”的Word文档
    css装饰文本框input
    css中background-image背景图片路径设置
  • 原文地址:https://www.cnblogs.com/shamoguzhou/p/6904582.html
Copyright © 2011-2022 走看看