链表的操作-三种插入法,删除,打印
//链表有序插入和删除最重要的是预判,就是判断下一个是否满足要求,因为如果只是判断当前,那么当你找到要操作的节点时,已经过了指向该节点的指针
//删除的时候注意释放空间
#include<stdio.h>
#include<stdlib.h>
typedef struct list
{
int data;
struct list*next;
}List;
void insert_list_2nd(List*head,int data);//表头插入
void insert_list_last(List*head,int data);//表尾插入
void insert_list_order(List*head,int data);//有序插入
void delete_list(List*head,int value);//从链表中删除元素
void print_list(List*head);//打印链表
int main()
{ int i;
List*head=(List*)malloc(sizeof(List));
head->data=-1;
head->next=NULL;//建立头结点
//for(i=0;i<10;i++)
//insert_list_2nd(head,i);
//insert_list_last(head,i);
for(i=9;i>=0;i--)
insert_list_order(head,i);
print_list(head);
//delete_list(head,5);
for(i=0;i<10;i++)
delete_list(head,i);
print_list(head);
}
void insert_list_2nd(List*head,int data)
{
List*newnode=(List*)malloc(sizeof(List));
newnode->data=data;
newnode->next=head->next;
head->next=newnode;
}
void insert_list_last(List*head,int data)
{ List*newnode=(List*)malloc(sizeof(List));
newnode->data=data;
newnode->next=NULL;
while(head->next!=NULL)
{
head=head->next;
}
head->next=newnode;
}
void insert_list_order(List*head,int data)
{
List*newnode=(List*)malloc(sizeof(List));
newnode->data=data;
newnode->next=NULL;
if(head->next==NULL)//链表中除了头结点没有其他结点
{
head->next=newnode;
return ;
}
while(head->next && head->next->data<data)
{
head=head->next;
}
/* if(head->next==NULL)//要插入的数是最大的
{
head->next=newnode;
}
else//找到要插入的位置,未在最后
{
newnode->next=head->next;
head->next=newnode;
}*/
newnode->next=head->next;
head->next=newnode;
}
void delete_list(List*head,int value)
{ List*p;
while(head->next && head->next->data!=value)
{
head=head->next;
}
if(head->next==NULL)
{
printf("has no number of %d\n",value);
return ;
}
p=head->next;
head->next=head->next->next;
free(p);
}
void print_list(List*head)
{
while(head)
{
printf("%d\n",head->data);
head=head->next;
}
}