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;
}
示例
?
|