链表是数据结构里非常重要的一个东西,也是平常用的比较多的一个东西。下面简单的展示一下单向链表的创建和单向链表的一些基本操作。
#include <stdio.h>
#include <stdlib.h>
typedef int datatype;
typedef struct data
{
datatype num; //数据域
struct data *next; //指针域
}Data;
Data *request_head_node()
{
Data *head = (Data*) malloc(sizeof(Data));
if (head==NULL)
{
printf("malloc head fail\n");
return NULL;
}
head->next = NULL; //要让指针指向NULL,不能成为野指针
return head;
}
//创建新结点
Data *request_new_node(datatype data_num)
{
Data *new = (Data*) malloc(sizeof(Data));
if (new==NULL)
{
printf("malloc head fail\n");
return NULL;
}
new->num = data_num;
new->next = NULL; //要让指针指向NULL,不能成为野指针
return new;
}
//带头结点的头插
void insert_to_head(Data *head,Data *new)
{
new->next = head->next;
head->next = new;
//错误的头插
// if(head == NULL) {
// head = new;
// head->next = NULL;
// }
// else{
// new->next = head;
// head = new;
// }
}
//不带头结点的头插
Data *insert_to_head1(Data *head,Data *new)
{
new->next = head;
return new;
}
//尾插
void insert_to_last(Data *head,Data *new)
{
Data *cur = head;
while(cur->next)
{
cur = cur->next;
}
cur->next = new;
new->next = NULL;
}
//查找结点
void find_to_node(Data *head)
{
Data *cur = head;
datatype num;
printf("请输入要查找的结点:\n");
scanf("%d",&num);
while (cur)
{
if(cur->num==num)
{
printf("查找成功\n");
return;
}
cur = cur->next;
}
}
void Del_Minn(Data *head)
{
//head是带头结点的单链表,本算法是删除结点最小值的元素
Data *pre = head,*p = pre->next;
Data *minpre = pre,*min = p;
while(p!=NULL)
{
if(p->num<min->num)
{
min = p; //遇到更小的,重新更新min的值
minpre = pre; //同时minpre作为min的前驱结点,也要改变指向pre
//才能保证minpre始终在min的前面一个位置
}
pre = p;
p = p->next;
}
minpre->next = min->next;
free(min);
}
//有顺序插入
void insert_to_sequence(Data *head,Data *new)
{
Data *pre = head;
Data *cur;
if(head->next==NULL)
{
pre->next = new;
new->next = NULL;
}
else
{
cur = pre->next;
while(cur)
{
if(new->num>cur->num)
{
cur = cur->next;
pre = pre->next;
}
else
{
new->next = pre->next;
pre->next = new;
return;
}
}
pre->next = new;
new->next = NULL;
}
}
//遍历打印
void Print(Data *phead)
{
while(phead)
{
printf("%d->",phead->num);
phead = phead->next;
}
printf("NULL");
}
//反转链表
Data * reverse(Data *head)
{
Data *n1 = NULL,*n2 = head,*n3 = head->next;
while(n2)
{
//反转链表
n2->next = n1;
//迭代
n1 = n2;
n2 = n3;
if(n3)
{
n3 = n3->next;
}
}
return n1;
}
int main()
{
Data *head = request_head_node();
Data *new = NULL;
head->num = 0;
head->next = NULL;
int n;
while(1)
{
scanf("%d",&n);
if(n==0) break;
new = request_new_node(n);
// insert_to_head(head,new); //带头结点的头插
// insert_to_last(head,new); //尾插
// Print(head);
// insert_to_sequence(head,new); //有序插入
// insert_increasing(head,new);
head = insert_to_head1(head,new); //不带头结点的头插
// insert_to_head(head,new);
Print(head);
}
// find_to_node(head);
head = reverse(head); //反转链表
// delete_to_node(head);
// printf("000");
// Del_Minn(head);
// move_min(head);
Print(head);
return 0;
}
看完别忘了点个赞!