注册 登录
编程论坛 数据结构与算法

顺序表的链式存储的基本操作

浮烟醉 发布于 2019-09-27 23:32, 2055 次点击
程序代码:
#include<stdbool.h>
#include<stdio.h>
#include<stdlib.h>
typedef int ElementType;
typedef struct LNode *PtrToLNode;
struct LNode {
    ElementType Data;
    PtrToLNode Next;
};
typedef PtrToLNode Position;
typedef PtrToLNode List;
List MakeEmpty()
{
   
    List L;

 
    L = (List)malloc(sizeof(struct LNode));
    L->Next = NULL;

 
    return L;
}

 
int Length(List L)
{
    Position p;
    int cnt=0;
    p=L;
    while(p!=NULL)
    {
        p=p->Next;
        cnt++;
        
    }
    return cnt;
}
/* 带头结点的插入 */

bool Insert( List L, ElementType X, int i )
{ /* 这里默认L有头结点 */
    Position tmp, pre;
    int cnt=0;
    pre=L;
    while(pre && cnt<i-1)
    {
        pre=pre->Next;
        cnt++;
      }  
              
    if ( pre==NULL ||cnt!=i-1) {
        
        return false;
    }
    else {
        tmp = (Position)malloc(sizeof(struct LNode)); /* 申请、填装结点 */
        tmp->Data = X;
        tmp->Next = pre->Next;
        pre->Next = tmp;
        return true;
    }
}

 
/* 带头结点的删除 */
bool Delete( List L, int i )
{ /* 这里默认L有头结点 */
    Position tmp, pre;
    int cnt=0;

 
    pre=L;
    while(pre && cnt<=i-1)
    {
        pre=pre->Next;
        cnt++;
        
      }  
    if ( pre==NULL || cnt!=i-1||pre->Next==NULL) {
        
        return false;
    }
    else {
        tmp=pre->Next;
        pre->Next = tmp->Next;
        free(tmp);
        return true;
    }
}
int main(int argc,char** argv){
    List L=MakeEmpty();
    int n,op;
    int i;
    ElementType x;
    scanf("%d",&n);
    while(n--)
    {
        scanf("%d",&op);
        switch(op)
        {
            case 1:scanf("%d %d",&x,&i);
            Insert(L,x,i);
            break;
            case 2:scanf("%d",&i);
            Delete(L,i);
            break;
        }   
    }
    while(L!=NULL){
        printf("%d ",L->Data);
        L=L->Next;
               
    }
   
    return 0;
}

然后遍历输出后删除操作未运行成功,且有一长串不知道什么的数字输出是为什么,哪里错了,可以讨论一下咩
只有本站会员才能查看附件,请 登录
2 回复
#2
林月儿2019-09-28 20:51
试着在Insert,Delete方法首部打印一下参数
#3
林月儿2019-09-28 21:07
bool Delete( List L, int i )
{ /* 这里默认L有头结点 */
    Position tmp, pre;
    int cnt=0;
    pre=L;
    while(pre && cnt<=i-1)
    {
        pre=pre->Next;
        cnt++;
    }
    printf("cnt=%d,pre=%d\n,i=%d",cnt,pre->Data, i);


。。。。


        头结点没有设置值,所以不用管直接从第二个结点开始打印
        L=L->Next;
        while(L!=NULL){
            printf("%d ",L->Data);      
            L=L->Next;
        }
        return 0;
    }

[此贴子已经被作者于2019-9-28 21:09编辑过]

1