首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

資料結構實驗:單鏈表基本操作(插入、刪除、查前驅、顯示)完整需求翻譯與實現指導

     編輯:程式設計疑難解答

實驗需求翻譯

實現單鏈表及操作:

  1. 插入:給定 Key,找到該 Key 節點,在其後插入新節點。未找到報錯。
  2. 刪除:給定 Key,刪除該 Key 節點。未找到報錯。
  3. 查前驅:給定 Key,找到其前驅節點並印出。未找到報錯;若為首節點,印「header」。
  4. 顯示:順序印出所有節點 Key。空表印「empty」。

輸入文件格式

每行一條指令:

  • `i x y`:在 Key=x 後插入 Key=y
  • `i x -1`:在表頭插入 Key=x
  • `d x`:刪除 Key=x
  • `f x`:查 Key=x 的前驅
  • `p`:印整表

範例追蹤

i 3 -1  → [3]
i 4 3   → [3,4]
i 7 -1  → [7,3,4]
i 5 8   → 8不存在,印 "Insertion(5) Failed: element 8 is not in the list"
d 3     → [7,4]
i 2 7   → [7,2,4]
d 9     → 9不存在,印 "Deletion failed: element 9 is not in the list"
f 3     → 3不存在,印 "Could not find 3 in the list"
f 7     → 前驅是header,印 "Key of previous node of 7 is header"
f 2     → 前驅是7,印 "Key of previous node of 2 is 7"
p       → 印 "Key:7 Key:2 Key:4"

建議資料結構

typedef struct Node *PtrToNode;
typedef PtrToNode List;
typedef PtrToNode Position;

struct Node {
    int Key;
    PtrToNode Next;
};

List MakeEmpty(List L);          // 初始化空表(帶頭節點)
Position Find(List L, int Key);  // 查找節點
Position FindPrevious(List L, int Key); // 查前驅
void Insert(List L, int Key, Position P); // 在P後插入
void Delete(List L, int Key);    // 刪除Key節點
void PrintList(List L);          // 印表
void DeleteList(List L);         // 釋放記憶體

實現提示

  • **帶頭節點** 簡化邊界處理(表頭插入/刪除同樣邏輯)。
  • 讀取文件逐行解析,`sscanf`/`strtok` 分割指令。
  • 錯誤訊息**完全對齊**題目要求格式(大小寫、標點、空格)。
  • 測試邊界:空表操作、重複 Key(題目說無重複)、刪除後查前驅。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved