單鏈表的基本運算
阿新 • • 發佈:2018-12-02
實現單鏈表的基本運算:初始化、插入、刪除、求表的長度、判空、釋放。
(1)初始化單鏈表L,輸出L->next的值;
(2)依次採用尾插法插入元素:輸入分兩行資料,第一行是尾插法需要插入的字元資料的個數,第二行是具體插入的字元資料。
(3)輸出單鏈表L;
(4)輸出單鏈表L的長度;
(5)判斷單鏈表L是否為空;
(6)輸出單鏈表L的第3個元素;
(7)輸出元素a的位置;
(8)在第4個元素位置上插入‘x’元素;
(9)輸出單鏈表L;
(10)刪除L的第3個元素;
(11)輸出單鏈表L;
(12)釋放單鏈表L。
輸入格式:
兩行資料,第一行是尾插法需要插入的字元資料的個數,第二行是具體插入的字元資料。
輸出格式:
按照題目要求輸出
輸入樣例:
5
a b c d e
輸出樣例:
0
a b c d e
5
no
c
1
a b c x d e
a b x d e
#include <stdio.h> #include <malloc.h> //malloc 標頭檔案 typedef struct List //連結串列的節點 { char data; struct List *next; }*ListNode, listnode; bool initList(ListNode& node) //注意返回值 連結串列初始化 { node = (ListNode)malloc(sizeof(listnode)); node->next = NULL; return node->next!=NULL; } void createList(ListNode& node, char a[],int num) //連結串列產生 輸入由外部傳入 { char data; ListNode tempNode, pMove; pMove = node; for (int j =0; j<num; j++) { tempNode = (ListNode)malloc(sizeof(listnode)); pMove->next = tempNode; //使用了尾插 tempNode->data = a[j]; tempNode->next = NULL; pMove = tempNode; } } void//列印 輸出連結串列 show(ListNode node) { ListNode pMove=node->next; while (pMove != NULL) //迴圈遍歷 { printf("%c", pMove->data); if (pMove->next != NULL) //為了題目需要最後一個不輸出空格 printf(" "); pMove = pMove->next; } printf("\n"); } int showLen(ListNode node) //返回連結串列長度 { ListNode p = node->next; int i=0; while (p) { i++; p = p->next; } return i; } bool showEmpty(ListNode node) //判斷連結串列是否為空 { return node->next == NULL; } char showEle(ListNode node, int num) //判斷num位置的元素 { ListNode temp = node; for (int i = 0; i<num; ++i) { temp = temp->next; } return temp->data; } int showLocate(ListNode node, char data) //判斷data資料的位子 { int i = 0; ListNode temp = node; while (temp->data != data&&temp!=NULL) { i++; temp = temp->next; } if (temp == NULL) return 0; else return i; } bool insertEle(ListNode& node, int num, char data) //插入資料 { if (num <= 0) //判斷num是否是有效值 return false; ListNode pTemp = node; for (int i = 0; i<num - 1; ++i) // 插入需要找到插入的前一個點 { pTemp = pTemp->next; } if (pTemp==NULL) return false; else { ListNode temp = (ListNode)malloc(sizeof(listnode)); temp->data = data; temp->next = pTemp->next; pTemp->next = temp; return true; } } bool deleteEle(ListNode& node, int num) //刪除第i個元素 { if (num <= 0) return false; ListNode temp = node,p; for (int i = 0; i<num - 1&&temp!=NULL; i++) //找到刪除資料的前一個節點 { temp = temp->next; } if (temp==NULL&&temp->next==NULL) //判斷刪除點的前一個點和刪除點是否為空如果有一個為空說明該點不存在 return false; else { p = temp->next; //斷開刪除點的指標 temp->next = p->next; free(p); //釋放刪除點 return true; } } void deleteList(ListNode& node) //刪除連結串列 { ListNode p = node, q; while (p != NULL) { q = p->next; free(p); p = q; } node = NULL; } int main() { ListNode text; int num; scanf("%d", &num); //輸入資料個數 char *data=(char*)malloc(sizeof(char)*(num+1)); for (int i = 0; i < num; ++i) //輸入資料 { getchar(); scanf("%c", &data[i]); } bool a = initList(text); createList(text,data,num); printf("%d\n", a); show(text); //略 return 0; }
最後輸出沒有寫完整,希望同學們要看一下函式內容自行呼叫函式。