线性表的两种形式的定义与相关操作(单链表和顺序表)
Posted chenglin520
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了线性表的两种形式的定义与相关操作(单链表和顺序表)相关的知识,希望对你有一定的参考价值。
#include <stdio.h> #include <string.h> #include <malloc.h> #pragma warning(disable:4996) #define ERROR 0 #define OK 1 #define MAXSIZE 100 typedef int ElemType; typedef int Status; typedef struct LNode; typedef struct ElemType *elem; int length; int listsize; SqList; typedef struct LNode ElemType data; struct LNode *next; LNode,*LinkList; Status InitSqlist(SqList &L) //初始化顺序表 L.elem = new ElemType[MAXSIZE]; if (!L.elem) return ERROR; L.length = 0; L.listsize = MAXSIZE; return OK; Status InitLinkList(LinkList &L) //初始化单链表 L = (LNode*)malloc(sizeof(LNode)); if (!L) return ERROR; L->next = NULL; return OK; Status addLinkList(LinkList &L,LNode *p) //向单链表中添加数据 LNode *e; e = L; while(e->next) e = e->next; e->next = p; p->next = NULL; return OK; Status showLinkList(LinkList &L) //显示单链表的数据 printf("链表的数据依次为:\n"); LNode *e = L; while (e->next) printf("%d ", e->next->data); e = e->next; printf("\n"); return OK; Status showSqlist(SqList &L) //显示顺序表的数据 printf("顺序表数据为:\n"); for(int i = 0;i<L.length;i++) printf("%d ", L.elem[i]); printf("\n"); return OK; Status tranLinkList(LinkList &L) //就地逆置单链表 LNode *p,*q,*e; if (!L->next) return ERROR; p = L; q = p->next->next; p->next->next = NULL; while (q) e = q->next; q->next = p->next; p->next = q; q = e; return OK; Status unitSqList(SqList &a, SqList &b, SqList &c) //将顺序表a和b中相同的数按递增的顺序放入顺序表c中,表a和b中数据递增且不等 int i, j, k; i = 0; j = 0; k = 0; while (true) if (i > a.length || j > b.length) return OK; if (a.elem[i] > b.elem[j]) j++; continue; if (a.elem[i] < b.elem[j]) i++; continue; if (a.elem[i] == b.elem[j]) j++; c.elem[k] = a.elem[i]; c.length++; k++; continue; Status unitLinkList(LinkList &a, LinkList &b, LinkList &c) LNode *p, *q, *r; p = a->next; q = b->next; while (true) if (!p || !q) return OK; if (p->data > q->data) q = q->next; continue; if (p->data < q->data) p = p->next; continue; if (p->data == q->data) r = (LNode*)malloc(sizeof(LNode)); r->data = p->data; addLinkList(c, r); q = q->next; continue; void main() LinkList L,M,N; InitLinkList(L); InitLinkList(M); InitLinkList(N); int num1[10] = 1,2,3,4,5,6,7,8,9,10; int num2[10] = 3,4,5,6,7,9,10,11,12 ,13; for (int i = 0; i < 10; i++) LNode *p = (LNode*)malloc(sizeof(LNode)); LNode *q = (LNode*)malloc(sizeof(LNode)); p->data = num1[i]; q->data = num2[i]; addLinkList(L, p); addLinkList(M, q); unitLinkList(L, M, N); showLinkList(L); showLinkList(M); showLinkList(N); SqList A,B,C; InitSqlist(A); InitSqlist(B); InitSqlist(C); for (int j = 0; j < 10; j++) A.elem[j] = num1[j]; A.length++; B.elem[j] = num2[j]; B.length++; unitSqList(A, B, C); showSqlist(A); showSqlist(B); showSqlist(C);
以上是关于线性表的两种形式的定义与相关操作(单链表和顺序表)的主要内容,如果未能解决你的问题,请参考以下文章