链表:逻辑结果是顺序连接的,并不像顺序表那样物理相邻。
图中头文件为输入错误,应该改为头结点
#include<stdio.h>
#include<stdlib.h>
#include <time.h>
#define OK 1
#define FAIL -1
typedef struct node
{
int num;
struct node *next;
}Node,*Link;
void creat_link(Link *head)
{
*head = NULL;
}
int is_malloc(Link new_node)
{
if (new_node==NULL)
{
printf("malloc error!\n");
return FAIL;
}
return OK;
}
int creat_node(Link *new_node)
{
*new_node=(Link)malloc(sizeof(Node));
if (OK == is_malloc(*new_node))
{
return OK;
}
return FAIL;
}
void insert_node(Link *head,Link new_node)
{
new_node->next=*head;
*head=new_node;
}
void display_link(Link head)
{
Link p=NULL;
p=head;
if (head==NULL)
{
printf("link is empty\n");
return;
}
while (p!=NULL)
{
printf("%d\n",p->num);
p=p->next;
}
}
int insert_node_tail(Link *head,Link new_node)
{
Link p=NULL;
p=*head;
if (*head == NULL)
{
*head = new_node;
new_node->next=NULL;
}
else
{
while (p->next!=NULL)
{
p=p->next;
}
p->next=new_node;
new_node->next=NULL;
}
}
void clear_node(Link *head)
{
Link p=NULL;
p=*head;
while (*head!=NULL)
{
*head=(*head)->next;
free(p);
p=*head;
}
}
int insert_node_mid(Link *head,Link new_node,int loc)
{
Link p=NULL;
p=*head;
while (p->next!=NULL&&p->num!=loc)
{
p=p->next;
}
new_node->next=p->next;
p->next=new_node;
}
int insert_node_sort(Link *head,Link new_node)
{
Link p=NULL;
Link q=NULL;
p=q=*head;
while (p!=NULL&&p->num<new_node->num)
{
q=p;
p=p->next;
}
if (p==*head)
{
new_node->next=*head;
*head=new_node;
}
else
{
q->next=new_node;
new_node->next=p;
}
}
int delete_node(Link *head,int num)
{
Link p=NULL;
Link q=NULL;
q=p=*head;
if (NULL == *head)
{
printf("链表不存在\n");
}
else
{
while (p!=NULL&&p->num!=num)
{
q=p;
p=p->next;
}
if (NULL == p)
{
printf("没有该结点!\n");
}
else if (p==*head)
{
*head=(*head)->next;
free(p);
}
else
{
q->next=p->next;
free(p);
}
}
}
void reserv_link(Link *head)
{
Link p1=NULL,p2=NULL,p3=NULL;
if (*head == NULL)
{
printf("reverse: Link is empty!\n");
return;
}
p1=*head;
if (NULL==(*head)->next)
{
return;
}
p2=p1->next;
p3=p2->next;
while (p3!=NULL)
{
p2->next=p1;
p1=p2;
p2=p3;
p3=p3->next;
}
p2->next=p1;
(*head)->next=NULL; //头结点的下一个指向空,即头结点是尾
*head=p2; //p2是最后一个结点
}
int main()
{
Link head=NULL;
Link new_node=NULL;
creat_link(&head);
int i;
int loc;
int num;
srand((unsigned)time(NULL));
/*printf("请输入你要插入的位置:\n");
scanf("%d",&loc);*/
for ( i = 0; i < 10; i++)
{
if(OK == creat_node(&new_node))
{
new_node->num =rand()%100;
//new_node->num=i+1;
//insert_node(&head,new_node); 头插法
//insert_node_tail(&head,new_node); 尾指针
insert_node_sort(&head,new_node);
}
}
/*if (OK == creat_node(&new_node))
{
printf("请输入想要插入的值\n");
scanf("%d",&new_node->num);
insert_node_mid(&head,new_node,loc);
}*/
printf("insert_node_sort:\n");
display_link(head);
printf("请输入要删除的数:\n");
scanf("%d",&num);
delete_node(&head,num);
printf("删除后的有\n");
display_link(head);
reserv_link(&head);
printf("倒序:\n");
display_link(head);
clear_node(&head);
display_link(head);
}