考研終于結束了,本想着多玩幾天,在第一天看了全天的電腦後感覺腦袋不行了,可能是很久沒有這麼長時間看電腦了吧。看來上天注定讓我多看看書呀,最近在看《白鹿原》,一本非常好看的小說。
下面直接貼代碼吧:
LinkList.h
#pragma once
#include<stdio.h>
#include<stdlib.h>
typedef struct LNode{ //單連結清單節點
int data; //資料
LNode *next; //下一個節點指針
}LNode,*LinkList;
typedef struct List{ //單連結清單
LNode *L; //頭指針
int length; //連結清單長度
}List;
void InitL(List *Li, int length) { //初始化連結清單
Li->length = length;
Li->L = (LNode *)malloc(sizeof(LNode));
Li->L->next = NULL;
}
int GetElem(List *Li, int i) { //取第i個節點的資料
if (i > Li->length) {
printf("超過連結清單長度\n");
return -;
}
LNode* p = Li->L;
int j = ;
if (p->next&&j <= i - ){
p = p->next;
j++;
}
return p->data;
}
int LocalElem(List *Li, int e) { //按值查詢連結清單
LNode *p = Li->L;
for (int i = ; i < Li->length; i++) {
p = p->next;
if (p->data == e)
return i+;
}
return -;
}
void ListInsert(List *Li, int local, int e) { //在第local個節點處插入值為e的節點
if (local< || local>Li->length + ) {
printf("超過連結清單長度\n");
return;
}
LNode *p = Li->L;
for (int i = ; i < local - ; i++) {
p = p->next;
}
LNode *s = (LNode*)malloc(sizeof(LNode));
s->data = e; s->next = p->next;
p->next = s;
Li->length++;
}
void ListDelete(List *Li, int local) { //删除在第local處的節點
if (local< || local>Li->length) {
printf("超過連結清單長度\n");
return;
}
LNode *p = Li->L;
for (int i = ; i < local - ; i++)
p = p->next;
LNode *s = p->next;
p->next = s->next;
free(s);
Li->length--;
}
void CreatList_H(List *Li, int length, int *a) { //前插法建立連結清單
LNode *L = Li->L;
for (int i = length - ; i >= ; i--) {
LNode *p = (LNode*)malloc(sizeof(LNode));
p->data = a[i];
p->next = L->next;
L->next = p;
}
}
void CreatList_R(List *Li, int length, int *a) { //後插法建立連結清單
//LNode *L = Li->L;
LNode *r = Li->L;
for (int i = ; i < length; i++) {
LNode *p = (LNode*)malloc(sizeof(LNode));
p->data = a[i];
p->next = NULL;
r->next = p;
r = p;
}
}
void PrintList(List *Li) { //順序輸對外連結表
LNode *p = Li->L;
for(int i= ;i < Li->length;i++){
p = p->next;
printf("%d ", p->data);
}
printf("\n");
}
main.cpp
#include "LinkList.h"
int main() {
List *Li = (List*)malloc(sizeof(List));
int length = ;
InitL(Li, length);
int a[] = { ,,,,,,,,, };
CreatList_H(Li, length, a); //建立連結清單_前插法
//CCreatList_R(Li, length, a); //建立連結清單_後插法
PrintList(Li); //輸對外連結表
printf("%d\n", LocalElem(Li, ));//根據資料定位節點
printf("%d\n", GetElem(Li, )); //根據節點位置取資料
ListInsert(Li, , ); //在節點位置為10的地方插入資料為10的節點
PrintList(Li);
ListDelete(Li, ); //删除節點位置為11的節點
PrintList(Li);
return ;
}
結果: