链表



/***********************************
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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值