目錄😋
任務描述
相關知識
測試說明
我的通關代碼:
測試結果:
任務描述
本關任務:編寫一個程序實現單鏈表的基本運算。
相關知識
為了完成本關任務,你需要掌握:初始化線性表、銷毀線性表、判定是否為空表、求線性表的長度、輸出線性表、求線性表中某個數據元素值、按元素值查找、插入數據元素、刪除數據元素等。
測試說明
平臺會對你編寫的代碼進行測試:
測試輸入:
3
4
預期輸出:
(1)初始化單鏈表h
(2)依次采用尾插法插入a,b,c,d,e元素
(3)輸出單鏈表h:a b c d e
(4)單鏈表h長度:5
(5)單鏈表h為非空
(6)單鏈表h的第3個元素:c
(7)元素a的位置:1
(8)在第4個元素位置上插入f元素
(9)輸出單鏈表h:a b c f d e
(10)刪除h的第3個元素
(11)輸出單鏈表h:a b f d e
(12)釋放單鏈表h
開始你的任務吧,祝你成功!
我的通關代碼:
#include <iostream>#include <string>
using namespace std;
#define MAX_SIZE 100typedef char ElemType;typedef struct {ElemType data[MAX_SIZE];int length;
} SeqList;void InitList(SeqList &L) { L.length = 0; }void PrintList(SeqList L) {for (int i = 0; i < L.length; i++) {cout << L.data[i] << " ";}cout << endl;
}
int InsertList(SeqList *L, int i, ElemType e) {if (i < 1 || i > L->length + 1 || L->length >= MAX_SIZE)return 0;for (int j = L->length; j >= i; j--) {L->data[j] = L->data[j - 1];}L->data[i - 1] = e;L->length++;return 1;
}bool GetElem(SeqList L, int i, ElemType &e) {if (i < 1 || i > L.length)return false;e = L.data[i - 1];return true;
}int LocateElem(SeqList L, ElemType e) {for (int i = 0; i < L.length; i++) {if (L.data[i] == e)return i + 1;}return 0;
}bool ListInsert(SeqList &L, int i, ElemType e) {if (i < 1 || i > L.length + 1)return false;for (int j = L.length; j >= i; j--) {L.data[j] = L.data[j - 1];}L.data[i - 1] = e;L.length++;return true;
}bool ListDelete(SeqList &L, int i, ElemType &e) {if (i < 1 || i > L.length)return false;e = L.data[i - 1];for (int j = i; j < L.length; j++) {L.data[j - 1] = L.data[j];}L.length--;return true;
}int main() {SeqList L;InitList(L);int pos1, pos2;cin >> pos1 >> pos2;cout << "(1)初始化單鏈表h" << endl;char elements[] = {'a', 'b', 'c', 'd', 'e'};for (int i = 0; i < 5; i++) {InsertList(&L, i + 1, elements[i]);}cout << "(2)依次采用尾插法插入a,b,c,d,e元素" << endl;cout << "(3)輸出單鏈表h:";PrintList(L);cout << "(4)單鏈表h長度:" << L.length << endl;cout << "(5)單鏈表h為非空" << endl;ElemType e;if (GetElem(L, pos1, e)) {cout << "(6)單鏈表h的第" << pos1 << "個元素:" << e << endl;}int pos = LocateElem(L, 'a');cout << "(7)元素a的位置:" << pos << endl;ListInsert(L, pos2, 'f');cout << "(8)在第" << pos2 << "個元素位置上插入f元素" << endl;cout << "(9)輸出單鏈表h:";PrintList(L);ListDelete(L, pos1, e);cout << "(10)刪除h的第" << pos1 << "個元素" << endl;cout << "(11)輸出單鏈表h:";PrintList(L);cout << "(12)釋放單鏈表h";return 0;
}