C语言双向链表实现

C语言双向链表实现

链表是计算机编程中常用的一种数据结构,在大部分面向对象的编程语言中都会有封装好的类供用户直接使用,只有在数据结构课程中,老师才会要求学生用代码实现一个链表,而如果用C语言实现链表,除了要了解链表的特性之外,对于指针的操作也是一个重头戏。
开发环境:VS2013
开发系统:window7

头文件(TwoWayList.h)代码如下:

#ifndef TWOWAY_LIST
#define TWOWAY_LIST
struct Node{
    Node * prior;
    Node * next;
    int content;
};
typedef struct TwoWayList{
    Node *head;
    Node * tail;
    int size;
}List;
// 检查链表是否为空
int isEmptyList(List *);
// 初始化节点;
Node * initNode(int);
// 初始化链表
List * initList();
// 末尾插入节点
void addNode(List *, Node *);
// 指定位置插入节点
void insertNode(List *, Node *, int);
// 顺序输出
void sequentialPrint(List *);
// 倒序输出
void reversePrint(List *);
// 删除指定节点
void deleteNode(List *, int pos);
// 修改指定节点
void modifyNode(List *, int ,int);
// 查询指定节点
void queryNode(List *, int);
// 节点排序输出
void sortList(List *);
// 退出程序
void exit(List*);
#endif
该文件定义了节点和链表的结构体,并对一些常用的链表操作进行了声明。

具体的方法实现(TwoWayList.cpp)

#include "stdafx.h"
#include "TwoWayList.h"
#ifndef STDLIB
#define STDLIB
#include <stdlib.h>

#endif


// 检查链表是否为空
int isEmptyList(List * list){
    if (NULL == list || list->size == 0)
        return 1;
    else
        return 0;
}
// 初始化节点;
Node * initNode(int value){
    Node * node = (Node *)malloc(sizeof(Node));
    if (NULL != node) {
        node->content = value;
        node->prior = NULL;
        node->next = NULL;
    }
    else {
        printf("INSUFFICIENT MEMEORY SPACE!!! ");
    }
    return node;
}
// 初始化链表
List * initList() {
    List * list = (List *)malloc(sizeof(List));
    if (NULL != list) {
        list->size = 0;
        list->head = NULL;
        list->tail = NULL;
        return list;
    }
    else {
        printf("INSUFFICIENT MEMORY SPACE!!! ");        // 提示内存不足
    }
    return NULL;
}
// 末尾插入节点
void addNode(List * list, Node * node) {

    if (NULL == node) {
        printf("A NULL node is invalide  \n");
        return;
    }

    if (NULL == list) {
        list = initList(
  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值