/***********************************
Flie name:
Author:
Description:
Function:
***********************************/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/**********定义一个结构体**********/
typedef struct num
{
int date;
struct num *next;
}NUM;
/***********头插法建立链表*********/
NUM *creathead(NUM *head)
{
NUM *p;
int dat1;
int i = 0;
while( i < 3)
{
p = (NUM*)malloc(sizeof(NUM));
printf(" please input data:\n");
scanf("%d",&dat1);
p -> next = head -> next;
head -> next = p;
p -> date = dat1;
i++;
}
return head;
}
/**************输出链表************/
print(NUM *head)
{
NUM *p;
p = head -> next;
while( p != NULL)
{
printf("%d\n", p->date);
p = p->next;
}
}
/*******在链表中添加一个元素*******/
NUM *inserthead(NUM *head, int addnum, int adddate)
{
NUM *p,*q;
int j = 1;
p = head -> next;
while(p && j < addnum)
{
p = p-> next;
++j;
}
if(!p || j > addnum)
{
return 0;
}
q = (NUM *)malloc(sizeof(NUM));
q -> date = adddate;
q -> next = p -> next;
p -> next = q;
return head;
}
/***********删除一个结点***********/
NUM *deletehead(NUM *head,int deletenum)
{
NUM *p, *q;
int j = 1;
p = head -> next;
while( p && j < deletenum )
{
p = p -> next;
++j;
}
if(!p || j < deletenum )
{
return 0;
}
q = p -> next;
p -> next = q -> next;
free(q);
return head;
}
/**************主函数**************/
int main()
{
int addnum; //插入元素的位置//
int adddate; // 插入元素的数据//
int deletenum; //删除元素的位置//
NUM *head;
head = (NUM *)malloc(sizeof(NUM));//建立一个头结点,并为其分配内存空间//
head -> next = NULL;
head = creathead(head); //建立一个链表//
print(head); //输出链表//
printf("will you insert where?:\n");
scanf("%d\n",&addnum);
printf("will you inset what?:\n");
scanf("%d\n",&adddate);
head = inserthead(head,addnum,adddate);
print(head);
printf("will you delete where?:\n");
scanf("%d\n",&deletenum);
head = deletehead(head,deletenum);
print(head);
return 0;
}