c语言简单链表实现

#ifndef _LIST_H_
#define _LIST_H_
//避免重复包含----条件编译






typedef int DataType;


typedef struct node
{
DataType data;
struct node *next;
}Node, *Pnode;




//01创建节点
Pnode createNode(DataType data);
//02插入节点
int insertNextNode(Pnode p1, Pnode p2);
int insertDataBySort(Pnode *phead, DataType data);


//03查询
void printList(Pnode head);




//04删除
void destroyList(Pnode head);


#endif
#include <stdio.h>
#include <stdlib.h>
#include "list.h"
//创建节点
Pnode createNode(DataType data)
{
Pnode p = (Pnode)malloc(sizeof(Node));
if (p != NULL)
{
p->data = data;
p->next = NULL;
}
return p;
}
//插入节点
int insertNextNode(Pnode p1, Pnode p2)
{
if (p1 != NULL&&p2 != NULL)
{
if (p1->next == NULL)
{
p1->next = p2;
}
else
{
p2->next = p1->next;
p1->next = p2;
}
return 0;
}
return -1;
}


int insertDataBySort(Pnode *phead, DataType data)
{
if (phead == NULL)
{
return -1;
}
if (*phead == NULL)
{
*phead=createNode(data);
}
else
{
Pnode pnew = createNode(data);
Pnode p1 = *phead;




if (p1->data > data)//解决头指针插入问题
{
insertNextNode(pnew, p1);
*phead = pnew;
return 0;
}




Pnode pre = NULL;
while (p1 != NULL)
{
if (p1->data <data)
{
pre = p1;
}
p1 = p1->next;
}
insertNextNode(pre,pnew);
}
return 0;
}
//03查询
void printList(Pnode head)
{
if (head != NULL)
{
Pnode ptemp = head;
while (ptemp != NULL)
{
printf("%d\n", ptemp->data);
ptemp = ptemp->next;
}
printf("------------------------------\n");
}

}
//04删除
void destroyList(Pnode head)
{
if (head != NULL)
{
Pnode ptemp = head;
head = head->next;
free(ptemp);
}
}
test1()
{
      Pnode p1= createNode(1);
 Pnode p2 = createNode(2);
 Pnode p3 = createNode(3);
 insertNextNode(p1, p3);
 printList(p1);
 insertNextNode(p1, p2);
 printList(p1);
 getchar();


}
test2()
{
Pnode head = NULL;
insertDataBySort(&head, 2);
insertDataBySort(&head, 3);
printList(head);
//destroyList(head);
//head = NULL;
insertDataBySort(&head, 1);
insertDataBySort(&head, 4);


printList(head);
//destroyList(head);
//head = NULL;
//printList(head);


getchar();


}
int main()
{
//test1();
test2();


}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值