码迷,mamicode.com
首页 > 其他好文 > 详细

线性表

时间:2020-05-22 09:31:25      阅读:61      评论:0      收藏:0      [点我收藏+]

标签:error   erro   完成   exp   end   插入   ror   初始化   lse   

小编最近学习数据结构,附上有关代码:

线性表存储:1 顺序存储,  2 链式存储

一元多项式的相加:链式相加

#include<iostream>
#define MAX_SIZE 100
const int ERROR = -1;
const int OK = -1;
typedef int Status; typedef int ElemType;
using namespace std;
typedef struct sqlist
{
	int length;
	ElemType Elem_array[MAX_SIZE];
}SqList;
typedef struct Lnode
{
	ElemType data;
	struct Lnode* next;
}LNode;
typedef struct ploy
{
	float coef;  //系数部分
	int expn;     //指数部分
	struct ploy* next;
}Ploy;
//顺序表的初始化
//Status Init_SqList(SqList* L)
/*
{
	L->Elem_array = (ElemType*)malloc(MAX_SIZE*sizeof(ElemType));
	if (!L->Elem_array)return ERROR;
	else { L->length = 0; return OK; }
}
*/
Status Insert_SqList(SqList &L, int i, ElemType e)
{
	int j;
	if (i < 0 || !(L.length - 1))return ERROR;
	if (L.length >= MAX_SIZE)
	{
		cout << "线性表溢出" << endl;
		return ERROR;
	}
	for (j = L.length - 1; j >= i - 1; --j)
		L.Elem_array[j + 1] = L.Elem_array[j];
	L.Elem_array[i - 1] = e;
	L.length++;
	return OK;
}
Status Locate_Delete_SqList(SqList& L, ElemType x)
//针对线性表的定位删除 { int i = 0, k; while (i<L.length) { if (L.Elem_array[i] != x)i++; else { for (k = i + 1; k < L.length; k++) L.Elem_array[k - 1] = L.Elem_array[k]; L.length--; break; } } return 0; } Status Insert_LNode(LNode &L,int n, int x)
//在n个节点之后插入data为x的节点 { int k = 1; LNode* q,*p,*l; p = L.next; while (k < n) { p = p->next; k++; } q = new LNode; l = p->next; p->next = q; q->next = l; q->data = x; return 0; } Ploy* Add_ploy(Ploy* La, Ploy* Lb)
//一元多项式的相加 { Ploy* lc, * pc, * pa, * pb, * ptr; float x; lc = pc = La; pa = La->next; pb = Lb->next; while (pa != NULL && pb != NULL) { if (pa->expn < pb->expn) { pc->next = pa, pc = pa; pa = pa->next; } if (pa->expn>pb->expn) { pc->next = pb; pc = pb; pb = pb->next; } else { x = pa->coef + pb->coef; if (abs(x) <= 1.0e-6) { ptr = pa; pa = pa->next; free(ptr); ptr = pb; pb = pb->next; free(ptr); } else { pc->next = pa; pa->coef = x; pc = pa; pa = pa->next; ptr = pb; pb = pb->next; free(ptr); } } } return lc; } int main() { int a[]{ 1,2,3,4,5,6 }; SqList List{ 6,{1,2,3,4,5,6} }; //SqList* List{ Elem_array:a,length:6}; //手动完成初始化 /* for(int i=0;i<6;i++) List.Elem_array[i] = a[i]; List.length = 6; */ cout << "length "<<List.length<<endl; Insert_SqList(List, 2, 100); for (int i = 0; i < 7; i++) cout << List.Elem_array[i] << endl; Locate_Delete_SqList(List, 4); cout << "Delete one element:" << endl; for (int i = 0; i < 7; i++) cout << List.Elem_array[i] << endl; return 0; }

 

线性表

标签:error   erro   完成   exp   end   插入   ror   初始化   lse   

原文地址:https://www.cnblogs.com/a-runner/p/12935106.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!