赞
踩
InitList(&L):初始化表。构造一个空的线性表L,分配内存空间。
ListInsert(&L,i,e):插入操作。在表L中的第i个位置上插入指定元素e。
ListDelete(&L,i,&e):删除操作。删除表L中第i个位置的元素,并用e返回删除元素的值。
LocateElem(L,e):按值查找操作。在表L中查找具有给定关键字值的元素。
GetElem(L,i):按位查找操作。获取表L中第i个位置的元素的值。
其他常用操作:
Length(L):求表长。返回线性表L的长度,即L中数据元素的个数。
Empty(L):判空操作。若L为空表,则返回true,否则返回false。
PrintList(L):输出操作。按前后顺序输出线性表L的所有元素值。
DestroyList(&L):销毁操作。销毁线性表,并释放线性表L所占用的内存空间。
//不带头结点的单链表
#include<stdio.h>
#include<stdlib.h>
typedef struct LNode{
int data;
struct LNode *next;
}LNode,*LinkList;
//不带头结点的:初始化一个空的单链表
bool InitList(LinkList &L){
L = NULL;
return true;
}
//判断单链表是否为空
bool Empty(LinkList L){
return (L == NULL);
}
//1、头插法
LinkList List_HeadInsert(LinkList &L){
LNode *s;
int x;
scanf("%d",&x);
while(x!=9999){
s=(LNode*)malloc(sizeof(LNode));
s->data=x;
s->next=L;
L=s;
scanf("%d",&x);
}
return L;
}
//2、尾插法
LinkList List_TailInsert(LinkList &L){
LNode *s;
int x;
scanf("%d",&x);
if(Empty(L)){
s=(LNode*)malloc(sizeof(LNode));
s->data=x;
L=s;
}
LNode *r=L;
while(scanf("%d",&x)&&x!=9999){
s=(LNode*)malloc(sizeof(LNode));
s->data=x;
r->next=s;
r=s;
}
r->next = NULL;
return L;
}
//3、按序号查找结点值
LNode *GetElem(LinkList L,int i){
int j=1;
LNode *p=L;
if(i<1)
return NULL;//若i无效,返回NULL
while(p&&j<i){
p=p->next;
j++;
}
return p;//返回第i个结点的指针,若i大于表长则返回NULL
}
//4、按值查找表结点
LNode *LocateElem(LinkList L,int e){
LNode *p=L;
while(p!=NULL&&p->data!=e){//从第一个结点开始查找
p=p->next;
}
return p;//返回该结点指针,否则返回NULL
}
//5、按位序插入(不带头结点)
//在第i个位置插入元素e
bool ListInsert(LinkList &L, int i,int e){
if(i<1) //i值不合法 i应该大于等于1
return false;
if(i==1){ //如果在第1个位置
LNode *s=(LNode *)malloc(sizeof(LNode));
s->data=e;
s->next=L;
L=s;
return true;
}
//如果不是第一个位置,操作与带头结点的操作一样
LNode *p; //指针p指向当前扫描到的结点
int j=1;
p = L;//L指向第一个结点
while(p!=NULL && j<i-1){ //循环找到第i-1个结点
p=p->next;
j++;
}
if(p==NULL)
return false;
LNode *t = (LNode*)malloc(sizeof(LNode));
t->data=e;
t->next=p->next;
p->next=t;
return true;
}
//6、删除结点 (删除第i个结点)
bool ListDelete(LinkList &L, int i){
if(i<1) //i值不合法 i应该大于等于1
return false;
if(i==1){
L=L->next;
return true;
}
LNode *p; //指针p指向当前扫描到的结点
int j=1;
p = L;//L指向第一个结点
while(p!=NULL && j<i-1){ //循环找到第i-1个结点
p=p->next;
j++;
}
if(p==NULL)
return false;
LNode *q=p->next;
p->next = q->next;
free(q);
return true;
}
//7、求表长
int ListLength(LinkList L){
int cnt=0;
LNode *q=L;
while(q){
q=q->next;
cnt++;
}
return cnt;
}
//8、打印
void PrintList(LinkList L){
LNode *p=L;
while(p){
printf("%d ",p->data);
p=p->next;
}
printf("\n");
}
int main(void){
LinkList L;
InitList(L);
//List_HeadInsert(L) ;
List_TailInsert(L);
PrintList(L);
LNode *p = GetElem(L,1);
printf("查找的第1个数据为%d\n",p->data);
LNode *s = LocateElem(L,7);
printf("查找的值为7的是%d\n",s->data);
printf("在第1个位置插入88\n");
if(ListInsert(L,1,88)) PrintList(L);
printf("删除第1个位置的元素\n");
if(ListDelete(L,1)) PrintList(L);
int len=ListLength(L);
printf("length=%d\n",len);
return 0;
}
/*
1 2 3 4 5 6 7 9999
*/
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。