单链表的实现

#include <stdio.h>
#include <stdlib.h>

typedef struct list
{
     int data;
     struct list *next;
}List;

/*
function:初始化为带表头的单链表
input:void
output:List型指针
*/
List *initList(void)
{
     List *L = (List *)malloc(sizeof(List));
     L->data = 0;  //it means this list has o element, and is an empty list
     L->next = NULL;
     return L;
}

/*
function:从表头插入元素
input:待插入的int型数值,链表指针
output:null
*/
void headInsert(int data, List *L)
{
     List *newNode = (List *)malloc(sizeof(List));
     newNode->data = data;
     newNode->next = NULL;

     newNode->next = L->next;
     L->next = newNode;
     L->data ++;
}

/*
function:display the list
input:链表指针
output:void
*/
void displayList(List *L)
{
     List *p = L;
     if(L->next == NULL)
     {
          printf("This is an empty List\n");
          return ;
     }
     while(p->next != NULL)
     {
          p = p->next;
          printf("%3d",p->data);
     }
     printf("\n");
}

/*
function:get node at pos position and delete it from the list
input:position and list
output:elemant with type of int
*/
//pos = 0 means the first data not the head list, so if the list length is n,then the biggest pos is n-1
int deleElem(int pos, List *L)
{
     int i = 0;
     int value = 0;
     List *p = L, *temp = NULL;
    
     if(pos < 0 || pos >= L->data)
     {
          printf("error: Wrong pos which is not in the list\n");
          exit(1);
     }
     for(i = 0; i < pos; i ++)
     {
          p = p->next;
     }
     temp = p->next;
     p->next = temp->next;
     value = temp->data;
     free(temp);

     L->data --;

     return value;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值