建立一个包含若干整数(比如1,2,3,4,5)的单向链表,然后通过某些算法,将其中的数据翻转(比如5,4,3,2,1)
更多资料请点击:我的目录
本篇仅用于记录自己所学知识及应用,代码仍可优化,仅供参考,如果发现有错误的地方,尽管留言于我,谢谢!
运行结果:
#include <stdio.h>
#include <stdlib.h>
struct node//设计节点
{
int data;
struct node *next;
};
struct node *list()//初始化一个带头节点的空链表
{
struct node *head = malloc(sizeof(struct node));
if(head != NULL)
{
head->next = NULL;
}
return head;
}
struct node *new_list(int data)//创建一个新的节点
{
struct node *new = malloc(sizeof(struct node));
if(new != NULL)
{
new->data = data;
new->next = NULL;
}
return new;
}
void list_link(struct node *head, struct node *new);//节点连接
void show_list(struct node *head);//输出链表所有节点
void over_turn(struct node *head);//链表翻转
int main()
{
struct node *head;
head = list();
printf("请输入将要插入的整数个数:");
int n;
scanf("%d", &n);
for(int i = 1; i <= n; i++)
{
struct node *new = new_list(i);
list_link(head , new);
}
printf("翻转前:");
show_list(head);
over_turn(head);
printf("翻转后:");
show_list(head);
return 0;
}
void list_link(struct node *head, struct node *new)//节点连接
{
if(head != NULL || new != NULL)
{
struct node *tail = head;
while(tail->next != NULL)
{
tail = tail->next;
}
tail->next = new;
}
}
void show_list(struct node *head)//输出链表所有节点
{
while(head->next != NULL)
{
head = head->next;
printf("%d\t",head->data);
}
printf("\n");
}
void over_turn(struct node *head)//链表翻转
{
struct node *p = head->next;
head->next = NULL;
while( p != NULL)
{
struct node *temp = p->next;
p->next = head->next;
head->next = p;
p = temp;
}
}
更多资料请点击:我的目录
还没有评论,来说两句吧...