C语言单向链表的反转实现
程序员文章站
2024-03-06 22:08:44
...
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int value;
struct node *next;
} nodes;
nodes *LinkList_Init();
void Insert_value(int value_in, nodes *P_node);
void Insert_pos_value(int value_in, int pos, nodes *p_node);
void Foreach_Linklist(nodes * p_node);
void Reserve_LinkList(nodes *p_node);
int main() {
printf("---开始创建链表---\n");
nodes* p_head = LinkList_Init();
printf("---链表创建完毕---\n");
printf("---开始后插数据--\n");
Insert_value(1, p_head);
Insert_value(2, p_head);
Insert_value(3, p_head);
Insert_value(4, p_head);
Insert_value(5, p_head);
Insert_value(6, p_head);
printf("---后插数据完毕---\n");
Foreach_Linklist(p_head);
printf("---开始反转链表--\n");
Reserve_LinkList(p_head);
printf("---反转链表完毕---\n");
Foreach_Linklist(p_head);
system("pause");
return 0;
}
//链表初始化
nodes *LinkList_Init() {
nodes *p_node = (nodes*)malloc(sizeof(nodes));
p_node -> next = NULL;
return p_node;
}
//往后插入数据
void Insert_value(int value_in, nodes *P_node) {
if(P_node == NULL)
return;
nodes *p_current = P_node;
nodes *new_node = (nodes*)malloc(sizeof(nodes));
new_node -> value = value_in;
new_node -> next = NULL;
while(p_current -> next != NULL) {
p_current = p_current -> next;
}
p_current -> next = new_node;
}
//遍历链表
void Foreach_Linklist(nodes *p_node) {
if(p_node == NULL)
return;
nodes * p_current = p_node -> next;
while(p_current != NULL) {
printf("%d\n", p_current -> value);
p_current = p_current -> next;
}
}
//链表反转
void Reserve_LinkList(nodes *p_node) {
if(p_node == NULL)
return;
nodes *p_privious = p_node -> next;
nodes *p_current = p_privious -> next;
p_privious -> next = NULL;//链表尾置空
if(p_current == NULL || p_privious == NULL)
return;
while(p_current != NULL) {
nodes *p_next = p_current -> next;
p_current -> next = p_privious;
p_privious = p_current;
p_current = p_next;
}
p_node -> next = p_privious;//链表头重新指向
}
上一篇: python单向循环链表
下一篇: 单向循环链表