#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();
}
c语言简单链表实现
最新推荐文章于 2022-12-27 11:25:26 发布