之前讲过单向链表,就不多说了哦。
代码文件: main.c、singly_link.c、my_singly_link.h
首先是 my_singly.h 的代码
#ifndef MY_SINGLY_LINK_H
#define MY_SINGLY_LINK_H
#include
#include
typedef struct MY_LIST
{
int data;
struct MY_LIST * Next;
}M_L,*P_M_L;
P_M_L Create_Node();
P_M_L Find_Node(P_M_L Head,int find_data);
int Add_Node(P_M_L Head);
int Display_List(P_M_L Head);
int Del_Node(P_M_L Head);
#endif // MY_SINGLY_LINK_H
接下来是 signly_link.c 的代码
#include "my_singly_link.h"
P_M_L Create_Node()
{
P_M_L Node = (P_M_L) malloc(sizeof(M_L));
if(Node == NULL) return NULL;
Node->Next = Node;
return Node;
}
int Add_Node(P_M_L Head)
{
if(Head == NULL) return -1;
P_M_L add_node = Create_Node(); //新建新的结点用来拼接在链表的头节点后面
if(add_node == NULL) return -1;
printf("请输入要添加的数据:");
scanf("%d",&add_node->data);
add_node->Next = Head->Next;
Head->Next = add_node;
return 0;
}
int Display_List(P_M_L Head)
{
if(Head == NULL || Head->Next == Head) return -1;
P_M_L new_node = Head->Next;
for(;new_node != Head; new_node = new_node->Next)
printf("%d\n",new_node->data);
return 0;
}
P_M_L Find_Node(P_M_L Head,int find_data)
{
if(Head == NULL || Head->Next == Head) return NULL;
P_M_L new_node = Head->Next;
for(;new_node != Head; new_node = new_node->Next)
if(new_node->data == find_data)
return new_node;
return NULL;
}
int Del_Node(P_M_L Head)
{
if(Head == NULL || Head->Next == Head) return -1;
int del_date;
printf("请输入要删除的数据:");
scanf("%d",&del_date);
P_M_L del_node = Find_Node(Head,del_date);
if(del_node == NULL) return -1;
P_M_L new_node = Head;
for(; new_node->Next != Head; new_node = new_node->Next)
if(new_node->Next == del_node)break;
new_node->Next = del_node->Next;
del_node->Next = NULL;
return 0;
}
最后是 main.c 的代码
#include "my_singly_link.h"
int main()
{
P_M_L Head = Create_Node();
if(Head == NULL) printf("创建节点失败 !\n");
int add_ret = Add_Node(Head);
if(add_ret == -1)printf("添加结点失败 ! \n");
Add_Node(Head);
Add_Node(Head);
Add_Node(Head);
int dis_ret = Display_List(Head);
if(dis_ret == -1)printf("显示链表数据失败 ! \n");
int del_ret = Del_Node(Head);
if(del_ret == -1)printf("删除失败 !\n");
dis_ret = Display_List(Head);
if(dis_ret == -1)printf("显示链表数据失败 ! \n");
return 0;
}