#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/*
1.创建
2.插入
3.排序
*/
typedef struct student
{
int data; //数据域名
struct student *next; //next指针
}node;
//创建链表
node *creat(void)
{
node* head;
head=(node*)malloc(sizeof(node)); //malloc开辟空间并且返回头指针
head->next=NULL; //设尾指针指向空
return head; //返回头指针
}
//插入链表
node *insert(node *head, int num)
{
node *p,*st,*next1,*news;
st = head;
p=(node*)malloc(sizeof(node));
while((st->data < num)&&(st->next != NULL))
{
next1 = st;
st = st -> next;
}
if(st->next == NULL&&st->data
{
st->next = p;
p->data = num;
p->next = NULL;
return head;
}else{
if(st==head) //判断插入位置是不是链首
{
p->next=st;
p->data=num;
return p;
}else{ //判断插入位置是不是链表中间
p->next=st;
p->data=num;
next1->next=p;
return head;
}
}
}
//计算链表长度
int length(node *head)
{
node *p;
p=head;
int count=0;
while(p->next!=NULL) //判断当前位置是否已到链尾
{
count++;
p=p->next;
}
count++;
printf("节点长度为%d\n",count);
}
//打印链表
void print(node *head)
{
node *p;
p=head;
while(p->next != NULL) //判断当前位置是否已到链尾
{
printf("节点的值为%d\n",p->data);
p=p->next;
}
printf("节点的值为%d\n",p->data);
}
node *del(node *head, int num)
{
node *p, *qian;
p=head;
while(p->data !=num && p->next !=NULL) //确定要删除的节点不在链尾
{
qian=p;
p=p->next;
}
if(p->data == num||p->next == NULL)
{
if(p==head&&p->next!=NULL) //删除的节点在链首且当前链表至少有两个节点
{
return p->next;
}else if(p->next==NULL&&p!=head)//删除的节点在链尾且当前链表至少有两个节点
{
qian->next=NULL;
return head;
}else if(p->data == num&&p->next == NULL){ //删除的节点所在链表只有一个节点
printf("该链表已经被彻底删除,不存在");
return NULL;
}else{
qian->next=p->next; //删除的节点在链表中
return head;
}
}else{
printf("当前链表没有该节点");
}
return head;
}
int main(void)
{
node* head={0};
head=creat(); //创建一个链表并返回一个头指针
head->data=12;
printf("ceshi %d\n",head->data);
head =insert(head,17);
head =insert(head,2);
head =insert(head,87);
head =insert(head,18);
head =insert(head,19);
head =insert(head,18);
head =insert(head,50);
head =insert(head,3);
print(head);
length(head);
head=del(head,17);
printf("---------------------\n");
printf("---------------------\n");
print(head);
return 0;
}