C代码实现非循环单链表

C代码实现非循环单链表,

直接上代码。

 # include <stdio.h>
# include <stdlib.h>
# include <malloc.h>
//C代码实现非循环单链表 //定义链表结点
typedef struct Node{
int data;//数据域
struct Node* pNext;//指针域
}* PNODE,NODE; //函数声明
PNODE initHead(void);
void init(PNODE pHead) ;
bool isEmpty(PNODE pHead);
void traverse(PNODE pHead);
int length(PNODE pHead) ;
bool insert(PNODE pHead,int pos,int num);
bool delete_linked(PNODE pHead,int pos); int main(void)
{
//确定一个非循环链表只需要一个头结点
PNODE pHead;
//初始化头结点
pHead = initHead();
//给链表赋值
init(pHead);
//遍历
traverse(pHead) ;
printf("\n");
printf("链表的结点为%d个\n",length(pHead));
// insert(pHead,3,99);
delete_linked(pHead,);
traverse(pHead) ;
return ;
} //向链表中某个位置增加一个结点 pos>=1
bool insert(PNODE pHead,int pos,int num)
{
int i = ;
PNODE tem = pHead;
//让tem指向第POS-1个节点
while(NULL!=tem&&i<pos-) {
tem = tem->pNext;
i++;
}
if(i>pos-||NULL==tem){
return false;
}
//分配一个新的结点
PNODE pNode = (PNODE)malloc(sizeof(NODE));
if(NULL==pNode){
printf("动态分配内存失败!\n");
exit(-);
}
pNode->data = num;
//第一种方式
// pNode->pNext = tem->pNext;
// tem->pNext = pNode;
// 第二种方式
PNODE p = tem->pNext;
tem->pNext = pNode;
pNode->pNext = p;
return true;
} //删除指定位置的值
bool delete_linked(PNODE pHead,int pos)
{
int i = ;
PNODE tem = pHead;
//让tem指向第POS-1个节点
while(NULL!=tem&&i<pos-) {
tem = tem->pNext;
i++;
}
if(i>pos-||NULL==tem){
return false;
}
PNODE p = tem->pNext;
tem->pNext = p->pNext;
free(p);
return true;
} //链表长度
int length(PNODE pHead)
{
int count = ;
PNODE tem = pHead->pNext;
while(NULL!=tem){
count++;
tem = tem->pNext;
}
return count;
} //初始化头结点
PNODE initHead(void)
{
PNODE pHead = (PNODE)malloc(sizeof(NODE));
if(NULL==pHead){
printf("申请内存失败\n");
exit(-);
}
return pHead;
} //给链表赋值
void init(PNODE pHead)
{
int num;//结点的值
int len;//结点的个数
printf("请输入结点的个数len= ");
scanf("%d",&len);
int i;
PNODE tem = pHead;
for(i = ;i<len;i++){
PNODE node = (PNODE)malloc(sizeof(NODE));
if(NULL==node){
printf("申请内存失败\n");
exit(-);
}
printf("请输入第%d个节点的值 ",i+);
scanf("%d",&num);
node->data = num;
tem->pNext = node;
node->pNext = NULL;
tem = node;
}
} //判断链表是否为空
bool isEmpty(PNODE pHead)
{
return (NULL==pHead->pNext);
} //遍历链表
void traverse(PNODE pHead)
{
if(isEmpty(pHead)){
printf("链表为空\n");
return;
}
PNODE tem = pHead->pNext;
while(NULL!=tem){
printf("%d ",tem->data);
tem = tem->pNext;
}
}
上一篇:vue.js的学习中的简单案例


下一篇:Golang 网络爬虫框架gocolly/colly 三