C语言链表四大操作:创建、释放、插入和删除

链表四大操作

  • 链表的创建 CreateList
  • 链表的释放 FreeList
  • 链表的插入 InsertNode
  • 链表的删除 DeleteNode
  • 附加一个打印 DisPlay
功能都封装在函数里且注释清楚,有需要直接转接口或者调用即可。
#include

typedef struct tagNode {
	int val;
	struct tagNode *next;
}List;

/*
 输入:构建链表长度Len
 功能:创建顺序单链表
*/
void CreateList(List *current,int Len) {
	int value;

	for (int i = 0; i < Len; i++) {
		List *temp = (List*)malloc(sizeof(List));
		if (temp == NULL) {
			exit(-1);
		}

		scanf("%d", &temp->val);
		temp->next = NULL;

		current->next = temp;
		current = current->next;
	}
}

/*
 输入:head原链表的头节点
 功能:顺序打印链表的节点
*/
void DisPlay(List *head) {
	List *current = head->next;
	if (current == NULL) {
		printf("LineList is empty");
		return;
	}
	while (current != NULL) {
		printf("%d", current->val);
		current = current->next;
	}
	printf("\n");
}

/*
 输入:head原链表的头节点
 功能:释放链表空间
*/
void FreeList(List *head) {
	List *current = head;
	if (current == NULL) {
		printf("LineList is empty");
		return;
	}
	while (head != NULL) {
		current = head;
		if (!head->next) {
			break;
		}
		head = head->next;
		free(current);
	}
}

/*
 输入:head原链表的头节点
      pos节点位置
 功能:删除pos位置的节点
*/
void DeleteNode(List *head,int pos) {
	if (pos <= 0) {
		return;
	}
	List *current = head;
	int i = 1;
	while (i < pos) {
		if (!current->next->next) {
			return;
		}
		current = current->next;
		i++;
	}
	current->next = current->next->next;
}

/*
 输入:head原链表的头节点
      NodeValue插入节点的值
      pos节点位置
 功能:在head链表中pos位置插入值为NodeValue的节点
*/
void InsertNode(List *head, int NodeValue, int Pos) {
	List *current = head;
	List *newNode = (List*)malloc(sizeof(List));
	newNode->val = NodeValue;
	int i = 1;
	while (i < Pos) {
		if (!current->next) {
			return;
		}
		current = current->next;
		i++;
	}
	newNode->next = current->next;
	current->next = newNode;
}

int main()
{
	int listCount = 3;// 链表长度

	List *current = (List*)malloc(sizeof(List));
	if (current == NULL) {
		exit(-1);
	}
	List *head = current;

	CreateList(current,listCount);// 构建链表

	DisPlay(head);// 原链表
	DeleteNode(head, 2);
	DisPlay(head);// 删除位置为2的及节点节点

	InsertNode(head, 8, 2);
	DisPlay(head);// 插入位置为2,数值为8的节点
	FreeList(head);

	system("pause");
	return 0;
}
main函数测试样例为:123

C语言链表四大操作:创建、释放、插入和删除_第1张图片

你可能感兴趣的:(C语言基础)