#include<stdio.h>
#include<stdlib.h>
#define ERR 0
#define OK 1
struct node()
{
int num;
struct node * next;
}
typedef struct node Node;
typedef struct node * Link;
void create_new_link(Link *head)
{
*head = NULL;
}
int judge_node(Link new_node)
{
if(new_node == NULL)
{
return ERR;
}
else
{
return OK;
}
}
create_new_node(Link *new_node,i)
{
do
{
*new_node = (Link)malloc(sizeof(Node));
}while(judge_node(*new_node) == ERR);
(*new_node)->num = i;
}
void insert_new_node_head(Link new_node,Link * head)
{
new_node->next = *head;
*head = new_node;
}
void insert_new_node_tail(Link new_node,Link * head)
{
Link p;
p = *head;
if(p == NULL) //如果头指针为NULL,即链表为空链表,那么头指针指向新结点
{
*head = new_node;
new_node->next = NULL;
}
else
{
while(p->next != NULL)
{
p = p->next;
}
p->next = new_node; //如果p的指针域为NULL,则p为末尾结点,从该点插入
new_node-next = NULL;
}
}
display_head(Link head)
{
Link p;
p = head;
if(p = NULL)
{
printf("Link is empty \n");
}
else
{
while(p != NULL)
{
printf("num = %d\n"p->num);
p = p->next;
}
}
}
void fanzhuan(Link *head)
{
Link p1,p2,p3,p;
p1 = p2 = p3 = p = *head;
if(*head == NULL && p1->next ==NULL)
{
return;
}
p2 = p2->next;
if(p2->next == NULL)
{
p2->next = p1;
p1->next = NULL;
*head = p2;
}
p3 = p2->next;
while(p3 != NULL)
{
p2->next = p1;
p1 = p2;
p2 = p3;
p3 = p3->next;
}
p2->next = p1;
*head = p2;
p->next = NULL; //?????
}
void insert_new_node_mid(Link new_node,Link *head,int num_val) //中插(前插)
{
Link p,q;
p = q = *head;
if(p == NULL) //情况1:如果头指针指向NULL,让头指针指向新结点
{
*head = new_node;
new_node->next = NULL;
}
else
{
if(p->num != num_loc && p->next ==NULL) //寻找待插入值的位置
{
q = p; //记录当前结点的位置
p = p->next; //p指向下一个结点
}
}
if(p == *head) //位置在头指针处,前插
{
new_node->next = *head;
*head = new_node;
}
if(p->next == NULL && p->num != num_loc) //未找到,插入到末尾
{
p->next = new_node;
new_node->next = NULL;
}
else //前插
{
q->next = new_node;
new_node-> = p;
}
}
void deleate_node(Link *head,Link num_del)//删除结点
{
Link p,q;
p = q = *head;
if(*head = NULL)
{
printf("Link IS EMPTY ");
}
else
{
while(p != num_del && p->next != NULL)
{
q = p; //记录当前结点的位置
p = p->next;
}
if((*head) == num_del)//待删除的数值位于头指针指向结点的值域,那么头指针直接指向下一个结点
{
*head ->next = *head;
free(p);
}
if(p->next ==NULL && p != num_del)
{
printf(" ERROR ");
}
else//在中间或者末尾
{
q->next = p->next;//???
free(p);
}
}
}
int main()
{
Link head;
Link new_node;
int num_loc,num_val,i,num_del;
create_new_link(&head);
for(i = 0;i < 10;i++)
{
create_new_node(&new_node,i);//创建新结点
insert_new_node_head(new_node,&head);//头插
insert_new_node_tail(new_node,&head);//尾插
}
display_head(&head);
fanzhuan(&head);
display_head(&head);
scanf("%d,%d",&num_loc,&num_val); //输入插入的地址位置和值
create_new_node(&new_node,num_val); //创建新的结点
insert_new_node_mid(new_node,&head,num_val); //在中间插入结点
display_head(&head);
scanf("%d",&num_del); //输入要删除的结点值
deleate_node(&head,num_del);
display_head(&head);
}
单链表的创建,头插,中间插入,尾插,结点的删除,反制,打印