陈某人又来了!之前双向链表讲过了,在这里就不多说了。
代码文件跟之前一样: main.c 、 singly_link.c 、singly_link.h
首先是singly_link.h的代码:
#ifndef _SINGLY_LINK_H
#define _SINGLY_LINK_H
#include
#include
#include
#define STRING_LENGTH 50
typedef char* STRING_KIND;
typedef struct singly_link
{
STRING_KIND string_data;
struct singly_link *next;
struct singly_link *prev;
}S_L,*P_S_L;
P_S_L Create_Node();
P_S_L Find_Node(P_S_L Head,STRING_KIND find_data);
int Add_Node(P_S_L Head);
int Display_List(P_S_L Head);
int Del_Node(P_S_L Head);
#endif // _SINGLY_LINK_H
接下来是 singly_link.c的代码 :
#include "singly_link.h"
P_S_L Create_Node()
{
P_S_L node = (P_S_L)malloc(sizeof(S_L));//给结点申请内存空间
if(node == NULL) return NULL;
node->string_data = (STRING_KIND)malloc(STRING_LENGTH); //给结点里面的指针申请空间
if(node->string_data == NULL) return NULL;
node->next = node;
node->prev = node;
return node;
}
int Add_Node(P_S_L Head)
{
if(Head == NULL) return -1;
P_S_L add_node = Create_Node();
if(add_node == NULL) return -1;
printf("请输入要添加的数据:");
fgets(add_node->string_data,STRING_LENGTH,stdin);
add_node->next = Head->next;
add_node->prev = Head;
Head->next->prev = add_node;
Head->next = add_node;
return 0;
}
int Display_List(P_S_L Head)
{
if(Head == NULL || Head->next == Head) return -1;
P_S_L new_node = Head->next;
while(new_node != Head)
{
printf("%s",new_node->string_data);
new_node = new_node->next;
}
return 0;
}
P_S_L Find_Node(P_S_L Head,STRING_KIND find_data)
{
if(Head == NULL || Head->next == Head) return NULL;
P_S_L new_node = Head->next;
while(new_node != Head)
{
if(strcmp(new_node->string_data,find_data) == 0) return new_node;
new_node = new_node->next;
}
return NULL;
}
int Del_Node(P_S_L Head)
{
if(Head == NULL || Head->next == Head) return -1;
STRING_KIND del_data[STRING_LENGTH];
printf("请输入要删除的数据:");
fgets(del_data,STRING_LENGTH,stdin);
P_S_L del_node = Find_Node(Head,del_data);
if(del_node == NULL) return -1;
del_node->prev->next = del_node->next;
del_node->next->prev = del_node->prev;
del_node->prev = NULL;
del_node->next = NULL;
free(del_node);
return 0;
}
最后是main.c的代码:(main.c主要是测试代码,随意自定义)
#include "singly_link.h"
int main()
{
P_S_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;
}