链表的课件整理,于VC++6.0中整理!
// 整理_线性表之链表.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
typedef int ElementType;
typedef struct Node
{
ElementType data;
struct Node *node;
}Node;
void InitList(Node **head);
void InitListAtHead(Node **head, ElementType data[], int n);
void InitListAtTail(Node **head, ElementType data[], int n);
int ListLength(Node *head);
bool IsListEmpty(Node *head);
void PrintList(Node *head, void (*fp)(ElementType data));
void Print(ElementType data);
bool DeleteElem(Node **head, int j, ElementType *e);
void Destroy(Node *head);
int main(int argc, char* argv[])
{
Node *head = NULL;
ElementType data[] = {1,2,3,4,5,6,7};
ElementType e = 0;
// InitListAtHead(&head, data, sizeof(data)/sizeof(data[0]));
InitListAtTail(&head, data, sizeof(data)/sizeof(data[0]));
PrintList(head, Print);
IsListEmpty(head);
ListLength(head);
DeleteElem(&head, -1, &e);
Destroy(head);
return 0;
}
//初始化链表,会创建一个无用节点,即head所指向的节点
void InitList(Node **head)
{
*head = (Node *)malloc(sizeof(Node));
(*head)->node = NULL;
}
//头部插入创建
void InitListAtHead(Node **head, ElementType data[], int n)
{
Node *p = NULL;
int i = 0;
InitList(head);
for(i=0; i<n; i++)
{
p = (Node *)malloc(sizeof(Node));
p->data = data[i];
p->node = (*head)->node;
(*head)->node = p;
}
}
//尾部插入创建
void InitListAtTail(Node **head, ElementType data[], int n)
{
Node *p = NULL, *q = NULL;
int i = 0;
InitList(head);
q = *head;
for(i=0; i<n; i++)
{
p = (Node *)malloc(sizeof(Node));
p->data = data[i];
p->node = NULL;
q->node = p;
q = p;
}
}
//返回链表长度
int ListLength(Node *head)
{
Node *p = head;
int cnt = 0;
while(p = p->node)
cnt++;
return cnt;
}
//链表是否为空
bool IsListEmpty(Node *head)
{
return head || head->node ? false : true;
}
//打印链表内容,需要一个函数作为参数
void PrintList(Node *head, void (*fp)(ElementType data))
{
Node *p = head->node;
while(p)
{
fp(p->data);
p = p->node;
}
}
//作为参数的函数
void Print(ElementType data)
{
printf("%d\n",data);
}
//删除第j个元素(从0计数),删除元素通过e返回
bool DeleteElem(Node **head, int j, ElementType *e)
{
int i = 0;
Node *p = NULL, *q = NULL, *r = NULL;
if(!(*head)->node || j<0 || j>ListLength(*head)-1)
{
return false;
}
else
{
p = *head;
q = p->node;
r = q->node;
for(i=0; i<j; i++)
{
p = p->node;
q = q->node;
r = r->node;
}
*e = q->data;
p->node = r;
free(q);
return true;
}
}
//销毁链表,释放内存
void Destroy(Node *head)
{
Node *p = head, *q = NULL;
while(p)
{
q = p->node;
free(p);
p = q;
}
}
main()中的测试是在VC++6.0中利用调试设置断点得出无误。如果读者发现代码有错误或者值得改进之处,请务必告知于我!