Java教程

算法与数据结构-单链表顺序表

本文主要是介绍算法与数据结构-单链表顺序表,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

#include<stdio.h>
#include<malloc.h>
#define ERROR 0
#define OK 1
#define MAXLEN 30
typedef int status;
typedef int Elemtype;
typedef struct
{ Elemtype *elem;
int length;
}Sqlist;
void creat(Sqlist &L){
int i,n;
L.elem = (Elemtype*)malloc(MAXLEN*sizeof(Elemtype*));
scanf("%d",&n);
L.length = n;
for(i = 0;i<n;i++){

scanf("%d",&L.elem[i]);
}
}
void output(Sqlist L){
int i;
for(i = 0;i<L.length;i++){
printf("%d",L.elem[i]);
}
printf("\n");
}
status list_insert(Sqlist &L,int i,Elemtype x){int j;
if(i<1||i>L.length) return ERROR;
if(L.length>MAXLEN) {return ERROR;
}
for(j = i-1;j<=L.length-1;j++)
L.elem[j+1] = L.elem[j];
L.elem[i-1] = x;
L.length++;
return OK;
}
status list_delete(Sqlist &L,int i,Elemtype &x){
int j;
if(i<1||i>L.length)return ERROR;
for(j = i;j<=L.length-1;j++)
L.elem[j-1] = L.elem[j];
L.length--;
return OK;
}
typedef struct Lnode{
Elemtype data;
struct Lnode*next;
}LNODE,*Linklist;
void creat2(Linklist &head){
int node;
Linklist p,r;
head = (Linklist)malloc(sizeof(LNODE));
head->next = NULL;
r = head;
scanf("%d",&node);
while(node!=0){
p = (Linklist)malloc(sizeof(LNODE));
p->data = node;
p->next = NULL;
r->next = p;
r = p;
scanf("%d",&node);
}
}
void output2(Linklist &head){
Linklist p;
for(p = head->next;p;p = p->next)
{printf("%d",p->data);
}
printf("\n");
}
status insert_list(Linklist &head,int i,Elemtype x){
Linklist r,p;
int j = 0;
p = head;
while(p!=NULL&&j<i-1){
p = p->next;
++j;
}
if(j>i-1||p == NULL)
return ERROR;
r = (Linklist)malloc(sizeof(LNODE));
r->data = x;
r->next = p->next;
p->next = r;
return OK;
}
int main(void){
Sqlist L;
creat(L);
output(L);
int i,x;
scanf("%d",&i);
scanf("%d",&x);
list_insert(L,i,x);
output(L);
list_delete(L,i,x);
output(L);
Linklist l;
creat2(l);
output2(l);
insert_list(l,i,x);
output2(l);
return 0;
}

这篇关于算法与数据结构-单链表顺序表的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!