您的位置:首页 > 其它

单循环链表(头指针指在头结点)『3』

2011-03-24 23:00 260 查看
为了便于学习单循环链表。

没有写那么多函数。

只写了一个插入函数。便于理解,这种情况下是,只有一个空的头结点,然后插入一个节点,既是在头部插入节点,也是在尾部插入节点。其他情况比这个情况都易于理解。所以只要会这一个,其他就都会了。

这个单循环链表(头指针指在头结点)。

强调:数据结构不是为了会写程序,只是利用程序设计语言来掌握一种思想。

/*
author:star
Data:2011.04.23
一个简单的单循环链表。
*/

#include<iostream>
#include<stdio.h>
#include<malloc.h>

using namespace std;
typedef int Status;
typedef int ElemType;

#define ERROR           0
#define OK                  1
#define LEN          sizeof( LNode )
#define OVERFLOW   0

typedef struct LNode
{
ElemType data;
struct LNode *next;
}LNode,*LinkList;

void InitList( LinkList &L )
{
L = ( LinkList ) malloc ( sizeof( LNode ) );
if( !L )
exit( OVERFLOW );
L ->next= L;
}

int ListLength( LinkList L )
{
LNode *p = L ->next ;
int length = 0;
while ( p!=L )
{
length++;
p = p->next;
}
return length;
}

Status ListInsert( LinkList &L, int i, ElemType e)
{//在带头结点的单循环链表中第i个位置之前插入元素e
if ( i < 1 || i > ListLength( L ) + 1 )
return ERROR;
LinkList p,s;
int j = 0;

p = L ->next;

while( ( p != L ) && j < i - 1 )//与单链表不同之处
{
p = p ->next;
j++;
}

s = ( LinkList ) malloc ( sizeof ( LNode ) );
s ->data = e;
s ->next = p ->next;
p ->next = s;
return OK;
}

void outList( LinkList L )
{
LinkList p;

p = L->next;
while( ( p != L ) )
{
cout << p ->data<< "     ";
p = p ->next;
}
cout << "/n";
}

int main()
{
LinkList head;
int i =0;

InitList( head );
i = ListInsert( head, 1, 5 );
if( i == ERROR ) cout << "Insert ERROR!";
else outList( head );

system("pause");
return 0;
}


VS2008下编译通过。调试成功。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: