C语言 链表

204 阅读1分钟

全局变量

  • gl_Head:表头指针
  • gl_Tail:表尾指针
  • gl_ListSize:表长度
  • gl_err:错误码

函数功能

  • initList():初始化链表
  • addNodeToList(int inHead, int value):添加新节点至表头或表尾
  • int getValueOfListByIndex(int index):根据索引获取节点内value值
  • void subNodeByIndex(int index):根据索引删除节点
  • ListNode* getNodeOfListByIndex(int index):根据索引获取节点的指针
  • int getListSize():获取表长度
  • ListNode* getListHead():获取表头指针

源文件

  • #include <stdlib.h>
  • #include <stdio.h>
  • #include "MyList.h"
  • ListNode* gl_Head;
  • ListNode* gl_Tail;
  • int gl_ListSize = 0;
  • int gl_err = 0;

void initList() {

    int i = 0;
for (;gl_ListSize>0;) {
	subNodeByIndex(0);
}

gl_Head = gl_Tail = NULL;
gl_ListSize = 0;
gl_err = 0;

}

void addNodeToList(int inHead, int value) {

ListNode* newNode = NULL;
ListNode* tmp = NULL;

if (inHead < 0 || inHead >1) {
	gl_err = -1;
	printf("error: 添加链表位置错误");
	return;
}

newNode = (ListNode*)malloc(sizeof(ListNode));
newNode->next = NULL;
newNode->value = value;

if (inHead == 0) {
	if (gl_ListSize == 0) {
		gl_Head = newNode;
		gl_Tail = newNode;
	}
	else {
		gl_Tail->next = newNode;
		gl_Tail = gl_Tail->next;
	}
	gl_ListSize++;
}
else {
	tmp = gl_Head;
	gl_Head = newNode;
	gl_Head->next = tmp;
	if (gl_ListSize == 0)
		gl_Tail = gl_Head;
	gl_ListSize++;
}

return;

}

int getValueOfListByIndex(int index){

int i = 0;
ListNode* tmp = NULL;
if (index <0 || index >gl_ListSize - 1) {
	gl_err = -1;
	printf("error: 索引超限");
	return -1;
}

tmp = gl_Head;
for (i = 0; i <= index; i++) {
	if (i == 0)
		continue;
	tmp = tmp->next;
}
	
return tmp->value;

}

void subNodeByIndex(int index) {

int i = 0;
ListNode* tmp = NULL;
if (index <0 || index >gl_ListSize - 1) {
	gl_err = -1;
	printf("error: 索引超限");
	return;
}

if (index == 0) {
	tmp = gl_Head;
	gl_Head = gl_Head->next;
	free(tmp);
	gl_ListSize--;
	return;
}
else if (index == gl_ListSize - 1) {
	gl_Tail = getNodeOfListByIndex(index-1);
	free(gl_Tail->next);
	gl_ListSize--;
	return;
}
else {
	tmp = getNodeOfListByIndex(index);
	getNodeOfListByIndex(index - 1)->next = getNodeOfListByIndex(index + 1);
	free(tmp);
	gl_ListSize--;
	return;
}
printf("error: 未删除节点");
return;

}

ListNode* getNodeOfListByIndex(int index) {

int i = 0;
ListNode* tmp = NULL;
if (index <0 || index >gl_ListSize - 1) {
	printf("error: 索引超限");
	gl_err = -1;
	return tmp;
}

tmp = gl_Head;
for (i = 0; i <= index; i++) {
	if (i == 0)
		continue;
	tmp = tmp->next;
}
return tmp;

}

int getListSize() {

return gl_ListSize;

}

ListNode* getListHead() {

return gl_Head;

} ListNode* getListTail() {

return gl_Tail;

}

头文件

typedef struct ListNode{ int value; struct ListNode * next; }ListNode;

  • void initList();
  • void addNodeToList(int inHead, int value);
  • int getListSize();
  • ListNode* getListHead();
  • ListNode* getListTail();
  • int getValueOfListByIndex(int index);
  • ListNode* getNodeOfListByIndex(int index);
  • void subNodeByIndex(int index);