OPSL
努力成为一名优秀的前端开发者!

原本是想着自己造好轮子之后就直接套用这些基本的struct和操作,但是转念一想还是将这些东西发到博客里分享一下。如果有错误还请各位大神指出

 


 

文件概述

  • linkNode.h  存放链表(结点结构以及结点指针),并对链表操作函数进行声明
  • linkNode.c  对之前在linkNode.h中声明的链表操作函数进行定义

 

代码

  linkNode.h

typedef int ElementType;
typedef struct LNode * List;

struct LNode{
ElementType Data;
List next;
};

//no_headNode_List
List MakeEmpty();                    //初始化一个空线性表 L
List FindKth(int K,List L);           //根据位序 K,返回相应元素
int Find(ElementType X,List L);         //在线性表 L 中查找 X 的第一次出现位置
void Insert(ElementType X,int i,List L);   //在位序 i 前插入一个新元素 X
void Delete(int i,List L);            //删除指定位序 i 的元素
int Length(List L);                  //返回线性表 L 的长度 n

 

  linkNode.c

#include <stdlib.h>
#include <stdio.h>
#include "linkNode.h"

 

//初始化一个空线性表 L
List MakeEmpty(){    
  List tempList = (List)malloc(sizeof(LNode));
  tempList->next = NULL;
  return tempList;
}

 

//根据位序 K,返回相应元素(从0开始)
List FindKth(int K, List L){
  List tempList = L;
  if(Length(tempList) < K + 1 || K < 0)
    return NULL;
  while(K){
    tempList = tempList->next;
    K--;
  }
  return tempList;
}

 

//在线性表 L 中查找 X 的第一次出现位置(从0开始,下标)
int Find(ElementType X, List L){
  int count = 0;
  List tempList = L;
  if(!L){                               //如果为空表,返回-1
    return -1;
  }
  while(tempList && X != tempList->Data){          //自身不为空,并且值不相等
    tempList = tempList->next;
    count++;
  }
  if(!tempList){                           //遍历完最后一个数,但是仍然没找到
    return -1;
  }
  else                                  //找到了
    return count;
 }

 

//在位序 i 前插入一个新元素 X(从0开始)
void Insert(ElementType X, int i, List L){
  List isrtNode = (List)malloc(sizeof(LNode));
  isrtNode->Data = X;
  isrtNode->next = NULL;
  if(i > Length(L)){                  //长度越界
    free(isrtNode);
    printf("Error");
    return;
  }
  List tempList = FindKth(i - 1, L);
  if(i != 0){                      //插入位置非首位
    isrtNode->next = tempList->next;
    tempList-> next = isrtNode;
  }
  else{                            //插入首位
    isrtNode->next = tempList;
  }
}

 

//删除指定位序 i 的元素(从0开始)
void Delete(int i,List L){
  List List_d = FindKth(i, L);
  if(!List_d){                       //位置错误
    printf("error");
    return;
  }
  if(i != 0){                        //删除位置为非头结点
    List tempList = FindKth(i - 1, L);
    tempList->next = List_d->next;
    free(List_d);
  }
  else{                            //删除位置为头结点
    List L = FindKth(i + 1, L);
    free(List_d);
  }
}

 

//返回线性表 L 的长度 n
int Length(List L){
  int len = 0;
  List tempList = L;
  while(tempList){
    len++;
    tempList = tempList->next;
  }
  return len;
}

 

posted on 2020-09-12 18:15  OPSL  阅读(318)  评论(0编辑  收藏  举报