原本是想著自己造好輪子之后就直接套用這些基本的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 = https://www.cnblogs.com/tomastu/p/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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/19472.html
標籤:C++
上一篇:多執行緒賣電影票,如何賣玩1000張電影票并統計耗時
下一篇:實驗1
