C语言写的简单的单向链表

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


typedef int T;


typedef struct Node
{
T data;
struct Node *next;
}Node;


//头结点创建
Node* CreateHead()
{
Node *p=(Node *)malloc(sizeof(Node));
if(p==NULL)
{
return NULL;
}
//初始化
memset(p,0,sizeof(Node));
return p;
}






//链表的遍历
int NodeList(Node *phead)
{
if(phead==NULL)
{
return -1;
}
Node *pCur=phead->next;
printf("head->");
while(pCur)
{
printf("%d->",pCur->data);
pCur=pCur->next;
}
puts("NULL");
return 0;
}
//头插法
int insertHead(Node *head,T data)
{
if(head==NULL)
{
return -1;
}
Node* pNew=(Node *)malloc(sizeof(Node));
if(pNew==NULL)
{
return -2;
}
pNew->data=data;
pNew->next=head->next;
head->next=pNew;
return 0;
}
//删除一个
int deleteNode(Node *head,T data)
{
if(NULL==head)
{
return -1;
}
Node *pCur=head;//指向上一个节点
Node *pNew=pCur->next;//指向下一个节点
while(pNew)
{
if(pNew->data==data)
{
pCur->next=pNew->next;
free(pNew);
break;
}
pCur=pNew;
pNew=pNew->next;
}
return 0;
}
//查找
Node* findNode(Node *head,T data)
{
if(head==NULL)
{
return NULL;
}
Node* pNew=head->next;
while(pNew)
{
if(pNew->data==data)
{
return pNew;
break;
}
pNew=pNew->next;
}
return NULL;
}


//节点释放
int freeNode(Node *phead)
{
Node *pNew=phead;
Node *pTmp;
if(pNew==NULL)
{
  return -1;
}


while(pNew)
{
pTmp=pNew->next;
free(pNew);
pNew=pTmp;
}
return 0;
}
//翻转
int reverseNode(Node *p)
{
if(p==NULL)
{
return -1;
}
Node *pCur=p->next;//保存第一个待插入节点
p->next=NULL; //空节点
Node *tmp;
while(pCur)
{
tmp=pCur->next;
pCur->next=p->next;
p->next=pCur;
pCur=tmp;
}
return 0;
}


//节点排序
int sort(Node *p)
{
if(p==NULL||p->next==NULL)
{
return -1;
}
Node *pCur;
Node *pNew;
Node tmp;
for(pCur=p->next;pCur!=NULL;pCur=pCur->next)
{
for(pNew=pCur->next;pNew!=NULL;pNew=pNew->next)
{
 if(pCur->data>pNew->data)
{
tmp=*pCur;
*pCur=*pNew;
*pNew=tmp;


tmp.next=pCur->next;
pCur->next=pNew->next;
pNew->next=tmp.next;
}
}
}


return 0;
}


int main()
{
Node *p=CreateHead();
int arr[]={21,234,213,21,324,213,342,12,34};
int len=sizeof(arr)/sizeof(int);
int i;
for(i=0;i<len;i++)
  insertHead(p,arr[i]);
  puts("初始化前");
NodeList(p);
puts("删除后");
  deleteNode(p,1);
NodeList(p);
puts("查找");
Node* tmp=findNode(p,2);
if(tmp)
{
printf("找到%d\n",tmp->data);
}
else
{
printf("没找到\n");
}
puts("翻转");
reverseNode(p);
NodeList(p);
puts("排序");
sort(p);
NodeList(p);
freeNode(p);
p=NULL;
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱写代码的马良

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值