您的位置:首页 > 理论基础 > 数据结构算法

数据结构之循环链表

2015-05-12 00:01 225 查看
循环链表与单链表相比,最大的特点就是其最后一个节点的指针域指向我们的头节点,其他方面与单链表并无二致。

节点结构:


链表结构:


不过和单链表不同的是,循环链表的表尾的指针域指向头节点,即:


下面上代码:

头文件List.h:

#ifndef _LIST_H
#define _LIST_H

#include<iostream>
#include<assert.h>
using namespace std;

#define ElemType int

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

typedef struct List
{
PNode first;
PNode last;
size_t size;
}List;

void InitList(List *list);
bool push_back(List *list, ElemType x);
void ShowList(List *list);
bool push_front(List *list,ElemType x);

#endif


函数实现List.cpp:

#include"List.h"

void InitList(List *list)
{
Node *s = (Node *)malloc(sizeof(Node));
assert(s != NULL);
list->first = list->last = s;
list->last->next = list->first;
list->size = 0;
}

bool push_back(List *list, ElemType x)
{
Node *s = (Node*)malloc(sizeof(Node));
if(s == NULL)
return false;
s->data = x;
s->next = NULL;

list->last->next = s;
list->last = s;
list->last->next = list->first;

list->size++;
return true;
}
bool push_front(List *list,ElemType x)
{
Node *s = (Node*)malloc(sizeof(Node));
if(s == NULL)
return false;
s->data = x;
s->next = NULL;

list->last->next = s;
list->last = s;
list->last->next = list->first;

list->size++;
return true;
}

void ShowList(List *list)
{
Node *p = list->first->next;
while(p != list->first)
{
cout<<p->data<<"-->";
p = p->next;
}
cout<<"Nul"<<endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: