为了准备笔试面试,重新复习了单链表系列的数据结构
下面分别写的是带头结点和不带头结点的尾插法单链表的创建以及他们的遍历!
看注释应该都可以理解了。
/*********************************************************************************
* Copyright: (C) 2021 li liangshi<1007146932@qq.com>
* All rights reserved.
*
* Filename: have_head.c
* Description: This file is 带头结点的尾插法单链表
*
* Version: 1.0.0(2021年09月07日)
* Author: li liangshi <1007146932@qq.com>
* ChangeLog: 1, Release initial version on "2021年09月07日 09时13分15秒"
*
********************************************************************************/
#include <stdlib.h>
#include <stdio.h>
/* 结点定义 */
typedef struct node_s
{
int value;
struct node_s *next;
}Node;
/* 声明头结点 */
Node *head;
/* 初始化头结点 */
void Init_head(Node **head)
{
*head =(Node *)malloc(sizeof(Node));
(*head)->next = NULL;
}
/* 尾插法插入结点 */
void Inser_list(Node **head)
{
int num;
int i;
int data;
Node *node, *r = *head;
printf("新建的单链表你想要插入多少个结点:");
scanf("%d", &num);
for(i=1; i<=num; i++)
{
printf("插入的第%d个结点:", i);
scanf("%d", &data);
node = (Node *)malloc(sizeof(Node));
node->value = data;
r->next = node;
r = node;
}
printf("长度为%d的单链表已经建好!", num);
}
/* 遍历带头结点的单链表 */
void Ergodic_list(Node *head)
{
Node *node;
printf("遍历单链表:");
while(head->next != NULL)
{
node = head->next;
printf("%d ", node->value);
head = node;
}
printf("遍历完成!\n");
}
int main (int argc, char **argv)
{
Init_head(&head);
Inser_list(&head);
Ergodic_list(head);
return 0;
}
/*********************************************************************************
* Copyright: (C) 2021 li liangshi<1007146932@qq.com>
* All rights reserved.
*
* Filename: nohave_head.c
* Description: This file is 不带头结点的尾插法单链表
*
* Version: 1.0.0(2021年09月07日)
* Author: li liangshi <1007146932@qq.com>
* ChangeLog: 1, Release initial version on "2021年09月07日 15时15分33秒"
*
********************************************************************************/
#include <stdio.h>
#include <stdlib.h>
/* 结点定义 */
typedef struct node_s
{
int value;
struct node_s *next;
}Node;
/* 声明头结点(全局) */
Node *head;
/* 初始化头结点 */
void Init_list(Node *head)
{
head = NULL;
}
/* 尾插法插入结点 */
void Insert_list(Node **head)
{
Node *r, *new_node;
int num, i, data;
printf("新建的单链表你想要插入多少个结点:");
scanf("%d", &num);
for(i=1; i<=num; i++)
{
printf("插入的第%d个结点为: ", i);
scanf("%d", &data);
new_node = (Node *)malloc(sizeof(Node));
new_node->value = data;
if(i == 1)
{
*head = new_node;
}
else
{
r->next = new_node;
}
r = new_node;
}
new_node->next = NULL;
}
/* 遍历不带头结点的单链表 */
void Ergodic_list(Node *head)
{
Node *node;
printf("遍历不带头结点的单链表:");
while(head != NULL)
{
node = head;
printf("%d ", node->value);
head = node->next;
}
printf("\n遍历完成!\n");
}
int main (int argc, char **argv)
{
Init_list(head);
Insert_list(&head);
Ergodic_list(head);
return 0;
}