代码改变世界

单链表的实现

2012-09-06 10:50  djky12  阅读(207)  评论(0)    收藏  举报

SLList.c函数

/*
功能:建立一个表,依次输入数据元素1,2,3,…,10,
然后删除数据元素5,最后依次显示当前表中的数据元素,
单链表实现。
*/
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>

typedef int DataType;//定义DataType为int
#include"SLList.h"//包括单链表操作

void main()
{
SLNode *head;//定义头指针
int i,x;

ListInitiate(&head);//初始化

for(i = 0;i < 10;i++)//插入10个元素
{
if(ListInsert(head,i,i+1) == 0)
{
printf("错误!\n");
return;
}
}

if(ListDeleta(head,4,&x) == 0)//删除第四个元素
{
printf("错误!\n");
return;
}

for(i = 0;i < ListLength(head);i++)//显示当前的数据元素
{
if(ListGet(head,i,&x) == 0)//取元素
{
printf("错误!\n");
return;
}
else
{
printf("%d ",x);//显示
}
}
Destroy(&head);//撤销单链表
}

 

SLList.h函数


typedef struct Node
{
DataType data;
struct Node *next;
}SLNode;

/*初始化*/
void ListInitiate(SLNode **head)
{
/*如果有内存空间,申请头结点空间并使头指针head指向头结点*/
if((*head = (SLNode *)malloc(sizeof(SLNode))) == NULL)
exit(1);
(*head)->next = NULL;//置结束标记NULL
}

/*求当前数据元素个数*/
int ListLength(SLNode *head)
{
SLNode *p = head;//p指向头结点
int size = 0;//size初始化为0

while(p->next != NULL)//循环计数
{
p = p->next;
size ++;
}
return size;
}

/*插入元素到指定位置*/
int ListInsert(SLNode *head,int i,DataType x)
{
SLNode *p,*q;
int j;

p = head;
j = -1;
while(p->next != NULL && j < i-1)
/*最终让p指向第i-1个结点*/
{
p = p->next;
j ++;
}
if(j != i-1)
{
printf("插入位置参数错!");
return 0;
}
/*生成新结点由指针q指示*/
if((q = (SLNode *)malloc(sizeof(SLNode))) == NULL)
exit(1);
q->data = x;

q->next = p->next;
p->next = q;
return 1;
}

/*删除*/
int ListDeleta(SLNode *head,int i,DataType *x)
{
SLNode *p,*s;
int j;
p = head;
j = -1;
while(p->next != NULL && p->next->next != NULL && j < i - 1)
/*最终让指针p指向第i-1个结点*/
{
p = p->next;
j ++;
}
if(j != i-1)
{
printf("删除位置参数错!");
return 0;
}

s = p->next;//指针s指向ai结点
*x = s->data;//把指针s所指结点的数据元素域值赋予x
p->next = p->next->next;//删除结点
free(s);//释放指针s所指向结点的内存空间
return 1;
}

 

/*取数据元素*/
int ListGet(SLNode *head,int i,DataType *x)
{
SLNode *p;
int j;

p = head;
j = -1;
while(p->next != NULL && j < i )
/*最终让指针p指向第i个结点*/
{
p = p->next;
j ++;
}
if(j != i)
{
printf("取元素位置参数错!");
return 0;
}

*x = p->data;//把指针p所指结点的数据元素域值赋予x
return 1;
}

/*撤销单链表*/
void Destroy(SLNode **head)
{
SLNode *p,*p1;
p = *head;
while(p != NULL)
{
p1 = p;
p = p->next;
free(p1);
}
*head = NULL;
}