C单链表

参考书 <<c语言数据结构和算法>> 清华大学出版社

#include <stdio.h>

typedef int ElemType;

typedef struct Node
{
  ElemType data;
  struct Node* next;
} Node; 

typedef struct LINKLIST
{
  int length;
  Node header; 
} LINKLIST; 

void InitList(LINKLIST*);  
int ListEmpty(LINKLIST*); 
int ListLength(LINKLIST*); 
void GetElem(LINKLIST*, int, ElemType *);  
void ListInsert(LINKLIST*, int, ElemType); 
void ListDel(LINKLIST*, int, ElemType *);  
void ClearList(LINKLIST*);  
void Destroy(LINKLIST*);   
#include <stdio.h>
#include <stdlib.h>
#include "linklist.h"

void InitList(LINKLIST* L)
{
  L->length = 0;
  L->header.next = NULL;
}

int ListEmpty(LINKLIST* L)
{
  if(L->length == 0)
    return 1;
  return 0;
}

int ListLength(LINKLIST* L)
{
  return L->length;
}

void GetElem(LINKLIST* L, int pos, ElemType* e)
{
  if(pos < 0  || pos >= L->length)
    return;
  if(L->length == 0)
    return;
  Node* pCur = &L->header;
  int i = 0;
  for(i=0;i<pos+1;i++)
    pCur = pCur->next;
  *e = pCur->data;
}

void ListInsert(LINKLIST* L, int pos, ElemType e)
{
  if(pos < 0 || pos >= L->length)
    return;
  Node* pCur= &L->header;
  int i=0;
  for(i=0;i<pos;i++)
    pCur=pCur->next;
  Node* pNew = (Node*)malloc(sizeof(Node));
  pNew->data = e;
  pNew->next = pCur->next;
  pCur->next = pNew;
  L->length++;
}

void ListDel(LINKLIST* L, int pos, ElemType* e)
{
  if(pos < 0 || pos >= L->length)
    return;
  if(L->length == 0)
    return;
  
  Node* pCur = &L->header;
  int i = 0;
  for(i=0;i<pos;i++)
    pCur = pCur->next;
  
  Node* pDel = pCur->next;
  *e = pDel->data;
  pCur->next = pDel->next;
  
  free(pDel);
  L->length--;
}

  
void ClearList(LINKLIST* L)
{
  while(ListEmpty(L) != 1)
  {  
    ElemType temp;
    ListDel(L, 0, &temp);
  }
}

void DestroyList(LINKLIST *L)
{
  ClearList(L);
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值