码迷,mamicode.com
首页 > 其他好文 > 详细

单链表的删除

时间:2017-05-25 16:44:45      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:overflow   lin   eof   next   存储位置   malloc   link   ret   size   

将表的第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!\n");
        }
        printf("\n");
}
结果:

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

单链表的删除

标签:overflow   lin   eof   next   存储位置   malloc   link   ret   size   

原文地址:http://www.cnblogs.com/shamoguzhou/p/6904582.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!