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

数据结构---线性表链式实现

2015-01-08 10:15 148 查看
主要参考的严老师那本教材上的:

写的比较快,可能代码的可读性不是很好。

//带头结点的单链表
#include <stdio.h>
#include <malloc.h>
#define ElemType int
typedef struct node
{
ElemType data;
struct node *next;
}node;

//用data来初始化并分配内存,返回一个新节点
node *newNode(ElemType data)
{
node *pNode=(node *)malloc(sizeof(node));
if(!pNode)
return NULL;//失败
pNode->data=data;
pNode->next=NULL;
return pNode;
}

//创建n个元素的链表(主要是分配空间),并且输入来初始化
node* createList(int n)
{
node *head=(node *)malloc(sizeof(node));
if(!head)
return NULL;//失败
head->next=NULL;
node *cur=head;
for (int i=0; i<n; i++)
{
ElemType tmp;
scanf("%d",&tmp);
node *tmpNode=newNode(tmp);
if(!tmpNode)
return NULL;//失败
cur->next=tmpNode;
cur=cur->next;
}
return head;
}

//输出链表所有元素
void printList(node *head)
{
node *cur=head;
while(cur->next!=NULL)
{
printf("%d ",cur->next->data);
cur=cur->next;
}
printf("\n");
}

//按照位置查找pos(除去头结点外,第一个元素算作位置0,从0开始)处元素,取得数据域
int searchByPos(node *head,int pos,ElemType *e)
{
node *cur=head;
for (int i=0; i<pos && cur->next!=NULL; i++)
cur=cur->next;
if(cur->next!=NULL)
{
*e=cur->next->data;
return 1;
}
else
return 0;

}

//在位置pos(前)插入一个新元素,pos:除去头结点外,有效节点的pos从0开始
//pos合法范围:0--len-1;不过程序中有检测
int insertByPos(node *head,int pos,ElemType e)
{
node *cur=head;
node *tmpNode=newNode(e);
int i;
if(!tmpNode)
return 0;//插入失败
for (i=0; i<pos && cur->next!=NULL; i++)
cur=cur->next;
if(cur->next==NULL&&i>=pos)//可以直接在尾部追加的情况
{
cur->next=tmpNode;
return 1;
}
else if(i>=pos)
{
tmpNode->next=cur->next;
cur->next=tmpNode;
return 1;
}
else
return 0;//pos位置不存在造成的无法插入

}

//删除某个位置的元素,用*e保存它的值
int deleteByPos(node *head,int pos,ElemType *e)
{
node *cur=head;
int i;
for (i=0; i<pos && cur->next!=NULL; i++)
cur=cur->next;
if(cur->next==NULL)
return 0;//不存在这个位置,删除失败
else
{
node *tmp=cur->next;
cur->next=cur->next->next;
free(tmp);
return 1;
}
}

int main()
{
node *head=createList(5);
printList(head);
insertByPos(head,3,55);
printList(head);
ElemType tmp;
deleteByPos(head,5,&tmp);
printList(head);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  线性表 单链表