数据结构第二章课后作业
设L的型为LIST线性表实例,x 的型为elementtype的元素
实例,p 为位置变量。所有操作描述为:
① INSERT(x, p, L)
② LOCATE(x, L)
③ RETRIEVE(p, L)
④ DELETE(p, L)
⑤ PREVIOUS(p, L), NEXT(p, L)
⑥ MAKENULL( L)
⑦ FIRST( L) ⑧END(L)
1.写一个算法合并两个已排序的线性表
伪代码:
定义一个函数: position Attach( int c ,position d) //建立一个新节点,并把它链接到d所指的节点之后,并返回这个新节点的指针 position linkadd(position A ,position B) { position p,q,d,c; Elymenttype x ; c = new node ; d = c; while (p!=END(a)&&q!=END(b)) { if(RETRIEVE(p, A)==RETRIEVE(q, B)) { d =Attach(RETRIEVE(p, A),d ) //将新节点链入 p=NEXT(p,A); q =NEXT(q,B); } else if (RETRIEVE(p, A)>RETRIEVE(q, B)) { d =Attach(RETRIEVE(p, A),d ) //将新节点链入 p=NEXT(p,A); } else { d =Attach(RETRIEVE(q, B),d ) //将新节点链入 q=NEXT(q,B); } } while(p!=END(A)) { d =Attach(RETRIEVE(p, A),d ) //将新节点链入 p=NEXT(p,A); } while(p!=END(B)) { d =Attach(RETRIEVE(q, B),d ) //将新节点链入 p=NEXT(q,B); } }
从C/C++
#include <iostream> #include<stdio.h> #include<stdlib.h> using namespace std; struct polynode { int exp; polynode *next; }; polynode *createapolylink() { int n, i, exp; polynode *head, *pre, *p; printf("输入链表长度 "); scanf_s("%d", &n); head = new polynode; head->next = NULL; pre = head; for (i = 0; i<n; i++) { printf("链表第%d个数", i + 1); p = new polynode; scanf_s(" %d", &exp); p->exp = exp; p->next = NULL; pre->next = p; pre = p; } return head; } void printfthepolylink(polynode *head) { polynode *p; p = head->next; while (p != NULL) { printf("%d ", p->exp); p = p->next; } } polynode *attach(int e, polynode *d) { polynode *x; x = new polynode; x->exp = e; d->next = x; return x; } polynode *polyadd(polynode* a, polynode *b) { polynode * p, *q, *d, *c; p = a; q = b; c = new polynode; d = c; while ((p != NULL) && (q != NULL)) { if (p->exp == q->exp) { d = attach(p->exp, d); p = p->next; q = q->next; } else if (p->exp>q->exp) { d = attach( p->exp, d); p = p->next; } else { d = attach( q->exp, d); q = q->next; } } while (p != NULL) { d = attach( p->exp, d); p = p->next; } while (q != NULL) { d = attach( q->exp, d); q = q->next; } d->next = NULL; p = c; c = c->next; delete p; return c; } int main() { polynode *link1, *link2, *link3; link1 = createapolylink(); link2 = createapolylink(); link3 = polyadd(link1, link2); printfthepolylink(link3); system("pause"); return 0; }
2.已知一个字符串,次序为3*-y -a/y ↑2,试利用栈把该字符串的次序变为3y-*ay2↑/-的操作步骤