上一篇实现了数组线性表的基本操作和顺序合并,这篇实现一下指针线性表(单链表)
基本操作:插入、删除、定位
顺序合并:依旧是尾插法,假定原表已经排好序
#include#include using namespace std; typedef int Elementtype; struct celltype { Elementtype element; celltype *next; }; typedef celltype *LIST; typedef celltype *position; position End(LIST L) { position q; q = L; while (q->next != NULL) q = q->next; return q; } void Insert(Elementtype x, position p) { position temp; temp = p->next; p->next = new celltype; p->next->element = x; p->next->next = temp; } void Delete(position p) { position q; if (p->next != NULL) { q = p->next; p->next = q->next; delete q; } } //定位 position Locate(Elementtype x, LIST L) { position p; p = L; while (p->next != NULL) { if (p->next->element == x) return p; else p = p->next; } return p; } position MakeNULL(LIST &L) { L = new celltype; L->next = NULL; return L; } LIST Mergetwo(LIST L1, LIST L2) { celltype *p = L1->next, *q = L2->next, *r, *s; LIST L3; L3 = (LIST)malloc(sizeof(celltype)); r = L3; while (p != NULL && q != NULL) { if (p->element < q->element) { s = (celltype *)malloc(sizeof(celltype)); s->element = p->element; r->next = s; r = s; p = p->next; } else { s = (celltype *)malloc(sizeof(celltype)); s->element = q->element; r->next = s; r = s; q = q->next; } } while (p != NULL) { s = (celltype *)malloc(sizeof(celltype)); s->element = p->element; r->next = s; r = s; p = p->next; } while (q != NULL) { s = (celltype *)malloc(sizeof(celltype)); s->element = q->element; r->next = s; r = s; q = q->next; } r->next = NULL; return L3; } int main() { Elementtype a[5] = {1, 3, 5, 7, 9}; Elementtype b[5] = {2, 4, 6, 8, 10}; LIST L1, L2; L1 = (LIST)malloc(sizeof(celltype)); //初始化结点使用malloc函数,需要重点了解 L2 = (LIST)malloc(sizeof(celltype)); celltype *print1 = L1, *print2 = L2; celltype *s1, *r1 = L1; celltype *s2, *r2 = L2; for (int i = 0; i < 5; i++) { s1 = (celltype *)malloc(sizeof(celltype)); s1->element = a[i]; r1->next = s1; r1 = s1; } r1->next = NULL; for (int j = 0; j < 5; j++) { s2 = (celltype *)malloc(sizeof(celltype)); s2->element = b[j]; r2->next = s2; r2 = s2; } r2->next = NULL; cout << "LIST1" << endl; while (print1->next != NULL) { cout << print1->next->element << " "; print1 = print1->next; } cout << "n" << "LIST2" << endl; while (print2->next != NULL) { cout << print2->next->element << " "; print2 = print2->next; } LIST L3; L3 = Mergetwo(L1, L2); cout << "n" << "LIST3" << endl; while (L3->next != NULL) { cout << L3->next->element << " "; L3 = L3->next; } return 0; }
主要参考: 《数据结构与算法》(第五版)张岩
《数据结构考研复习指导》(王道)



