﻿ 數據結構學習講座(C++) 單鏈表（２）_電腦知識網

# 數據結構學習講座(C++) 單鏈表（２）

2022-06-13   來源: 數據結構

單鏈表應用

有人曾經建議最好把鏈表和鏈表位置這兩個分開C++標准庫是這麼做的但對於初學者來說一個類總比兩個類好操作我不清楚在書中這部分的程序究竟調沒調試但這種語句我是絕對看不懂的

ListNode<Term> *pa *pb *pc *p;
ListIterator<Term> Aiter(ahpoly);
ListIterator<Term> Biter(ahpoly);
pa = pc = AiterFirst(); pb = p = BiterFirst();
………………………
pa>coef = pa>coef + pb>coef;
p = pb; pb = BiterNext(); delete p;

pa pb p 究竟指向什麼？你說這很清楚ListNode<Term>這樣的節點呗但按照原書的定義ListIterator::First()等等函數返回是指向data域的指針他們怎麼能直接賦值？到了下面更亂了pb指向的區域直接分解出了Term的數據成員也就是說是指向Term結構的然後讓ListNode<Term>類型的指針p指向這個Term結構最後居然把這個結構delete了天啊ListNode<Term>這樣的節點的data域被delete了！

一元多項式類定義與實現

#ifndef Polynomial_H
#define Polynomial_H

#include Listh
class Term
{
public:
int coef;
int exp;
Term() : coef() exp() {}
Term(int c int e) : coef(c) exp(e) {}
Term(int c) : coef(c) exp() {}
};

class Polynomial : List<Term>
{
public:
void Input()
{
cout << endl << 輸入多項式的各項系數和指數;
cout << endl << 注意請按降序輸入各項輸入系數表示結束 << endl;
int coef exp;
for(int i = ; ; i++)
{
cout << << i << 項的系數;
cin >> coef;
if (coef)
{
cout << 指數;
cin >> exp;
Term term(coef exp);
Insert(term);
}
else break;
}
}
void Print()
{
cout << endl;
First();
if (!IsEmpty())
{
Term *p = Next();
cout << p>coef;
if (p>exp)
{
cout << x;
if (p>exp != ) cout << ^ << p>exp;
}
while (Next() != NULL)
{
p = Get();
if (p>coef > ) cout << +;
cout << p>coef;
if (p>exp)
{
cout << x;
if (p>exp != ) cout << ^ << p>exp;
}
}
}
cout << endl;
}
friend void PolyAdd (Polynomial &polyA Polynomial &polyB)
{
Node<Term> *pA *pB;
polyAFirst();polyBFirst();
pA = polyApNext();pB = polyBpNext();
while (pA != NULL && pB !=NULL)
{
if (pA>dataexp == pB>dataexp)
{
pA>datacoef = pA>datacoef + pB>datacoef;
polyBRemove();
if (!pA>datacoef) polyARemove();
else polyApNext();
}
else
{
if (pA>dataexp > pB>dataexp)
{
polyBpRemove();
polyAInsertBefore(pB);
}
else if (pA>dataexp < pB>dataexp) polyApNext();
}
pA = polyApGet();pB = polyBpGet();
}
if (pA == NULL)
{