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(