C語言實現線性表(鏈式存儲方式)


#include <stdio.h>
#include <stdlib.h>  //提供malloc()原型

typedef struct LNode *List;
typedef int ElementType;
//定義數據結構的自定義名稱


struct LNode{
    ElementType Data;       //數據域
    List Next;              //指針域
};

struct LNode L;
List PtrL;

int Length(List PtrL) //鏈表頭指針
/*表長*/
{
    List p = PtrL;   //臨時的指針 p 指向表的第一個節點
    int j = 0;  //計數器作用
    while(p)  //遍歷單向鏈表
    {
        p = p->Next;
        j++;          //當前p指向的是第j個節點
    }
    return j;
}

List FindKth(int K,List PtrL)
/*查找-序號*/
{
    List p = PtrL;
    int i = 1;
    while (p!= NULL && i < K)
    {
        p = p->Next;
        i++;
    }
    if (i==K)
    {
        return p;  //找到K位置,返回指針
    }
    else
    {
        return NULL; //未找到,返回空
    }
}


List Find(ElementType X,List PtrL)
/*查找-值*/
{
    List p = PtrL;
    while (p != NULL && p->Data != X)
    {
        p = p->Next;
    }
    return p; //找到X,返回指針,未找到X,返回NULL
}


List Insert(ElementType X, int i, List PtrL)
/*插入*/
//步驟: 1、 構造一個新結點,用s指向
//      2、 找到鏈表的第i-1個結點,用p指向
//      3、 然后修改指針,插入結點
//      s-Next指向 p->Next,p->Next指向s,
{
    List p , s;
    if(i == 1) //表頭插入結點
    {
        s = (List )malloc(sizeof(struct LNode)); //申請結點空間
        s->Data = X;   //填充結點
        s->Next = PtrL;
        return s;
    }
    p = FindKth(i-1, PtrL);   //查找第i-1個結點
    if(p==NULL)
    {
        printf("參數%d錯誤",i);
        return NULL;             //i-1結點不存在
    }
    else
    {
        s = (List)malloc(sizeof(struct LNode)); //申請結點空間
        s->Data = X;
        s->Next = p->Next;
        p->Next = s;
        return PtrL;
    }
}

List Delete(int i, List PtrL)
/*刪除*/
{
    List p ,s;
    if(i==1)        //刪除表的第一個節點
    {
        s = PtrL;   //s指向第一個節點
        if (PtrL != NULL)
        {
            PtrL = PtrL->Next; //從鏈表中刪除
        }
        else
        {
            return NULL;
        }
        free(s);  //釋放s
        return PtrL;
    }
    p = FindKth(i-1 , PtrL); //查找第i-1個結點
    if (p == NULL)
    {
        printf("%d 節點不存在",i-1);
        return NULL;
    }
    else if (p ->Next == NULL)
    {
        printf("%d 節點不存在",i);
        return NULL;
    }
    else
    {
        s = p->Next;     //s 指向第i個結點
        p->Next = s->Next;  //從鏈表中刪除
        free(s);            //釋放被刪除的結點
        return PtrL;
    }
}


int main()
{
    int j;
    int i =1;
    List p;

    j=Length(PtrL);      //計算長度
    printf("當前長度:%d\n",j);

    PtrL=Insert(5,1,PtrL);  //在表頭插入結點

    p=FindKth(1,PtrL);
    printf("查找頭結點的值:%d\n",p->Data); //按照序號查找並打印結果

    p=Find(5,PtrL);
    printf("查找數值5:%d\n",p->Data); //按照值查找並打印結果

     printf("插入數值3\n");
    Insert(3,2,PtrL);  //插入操作

    p=Delete(1,PtrL);
    printf("刪除頭結點后,當前頭結點數值:%d\n",p->Data); //刪除頭結點

    j=Length(&L);      //計算長度
    printf("當前長度:%d\n",j);

    return 0;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM