C/C++教程

C语言之链表的基本操作(含代码)

本文主要是介绍C语言之链表的基本操作(含代码),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

head.h

#pragma once

#include <stdio.h>
#include <stdlib.h>
typedef struct number {
	int digit;
	struct  number *next;
}Number, *pNumber;
pNumber createNumberInfo();
void insertNumberInfo(pNumber pHead, pNumber pNew, int i);//插入到某个节点
void deleteNumberInfo(pNumber pHead, int i);
void displayNuberInfo(pNumber pHead);
void freeNumberInfo(pNumber pHead);

list.c

#include "head.h"

pNumber createNumberInfo()
{
	pNumber pHead, pTail, pNew;
	int digit;
	pHead = (Number*)malloc(sizeof(Number));
	if (NULL==pHead) {
		perror("Phead malloc error");
		return NULL;
	}
	pHead->next = NULL;
	pTail = pHead;
	printf("input a digit\n");
	while (1) {
		scanf("%d", &digit);
		if (digit < 0) {
			break;
		}
		pNew = (Number*)malloc(sizeof(Number));
		if (NULL==pNew) {
		perror("pNew malloc error");
		return 0;
		}
		pNew->digit = digit;
		pTail->next = pNew;
		pTail = pNew;
		pTail->next = NULL;
	}
	return pHead;
}
void insertNumberInfo(pNumber pHead, pNumber pNew, int i)
{
	pNumber pCur = pHead;
	for (int j = 0; j < i-1&&pCur!=NULL; ++j) {
		pCur = pCur->next;
	}
	if (NULL == pCur) {
		printf("not found\n");
		return ;
	}
	pNew->next = pCur->next;
	pCur->next = pNew;
}
void deleteNumberInfo(pNumber pHead, int i)
{
	pNumber pCur = pHead;
	pNumber q;
	if (0 == i) {
		return ;
	}
	for (int j = 0; j < i-1 ; ++j) {
		pCur = pCur->next;
	}
	q = pCur->next;
	pCur->next = q->next;
	free(q);
	q = NULL;
}
void displayNuberInfo(pNumber pHead)
{
	pNumber pCur = pHead->next;
	for (; pCur != NULL; pCur = pCur->next) {
		printf("%d ", pCur->digit);
	}
	printf("\n");

}
void freeNumberInfo(pNumber pHead)
{
	pNumber pCur = pHead;
	pNumber q;
	while (pCur->next != NULL) {
		q = pCur->next;
		pCur->next = q->next;
		free(q);
		q = NULL;
	}
	free(pHead);
	pHead = NULL;
}

main.c

#include "head.h"
int main()
{
	pNumber pHead, pTail, pNew;
	pHead = createNumberInfo();
	if (NULL == pHead) {
		printf("createNumberInfo error\n");
		return -1;
	}
	printf("after create:");
	displayNuberInfo(pHead);
	pNew = (Number*)malloc(sizeof(Number));
	pNew->digit = 0;
	insertNumberInfo(pHead,pNew,1);
	displayNuberInfo(pHead);
	deleteNumberInfo(pHead, 1);
	displayNuberInfo(pHead);
	freeNumberInfo(pHead);
	return 0;
}

示例

 

这篇关于C语言之链表的基本操作(含代码)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!